Property Delegation in C #

I am doing something with Odbc DataReader. Each line of the query result should be converted to ResultObject, as shown below:

struct ResultObject {
    public int Prop1 { get; set; }
    public string Prop2 { get; set; }
    ...
}

To write more code for the domain, I want to convert this code

var query = "SELECT Prop1, Prop2, ... FROM MyTable;";
... connect, submit query
while( reader.Read() ) {
  var fieldValue = fields[ fieldindex ];
  switch( fieldindex ) {
     case( indexProp1 ): result.Prop1.Set( (int) fieldValue); break;
     case( indexProp2 ): result.Prop2.Set( (string) fieldvalue); break;
     ...
  }
}

into something more general, where I build a mapping between indexes and "setters" dynamically:

But it would be nice to have something more concise:

PropMapper mappers[] = {
 new PropMapper("Prop1", ResultType.Prop1 ),
 new PropMapper("Prop2", ResultType.Prop2 ),
 ....
};

However, I do not know how to create PropMapperfrom a property ResultType.

Question:

How can I generate an object that wraps / delegates a property of a specific type?

Note: although ORMs are very useful for this, I really ask how C # allows you to create a delegate (or something similar)

+3
source share
3 answers

PropMapper - , . Prism NotificationObject RaisePropertyChanged.

, .

+2

Reflection:

PropertyInfo[] props = new PropertyInfo[]
{
  typeof(ResultObject).GetProperty("prop1"),
  typeof(ResultObject).GetProperty("prop2"),
};

for (int i = 0; i < props.Length; i++)
{
  props[i].SetValue(result, fieldValue, null);
}
+1

You might want to take a look at the mini-orm, for example dapper

0
source

All Articles