I want to populate an object\'s properties without using reflection in a manner similar to the DynamicBuilder on CodeProject. The CodeProject example is tailored for populat
Yeah,you can use code like this:
for (int i = 0; i < dataRecord.FieldCount; i++)
{
PropertyInfo propertyInfo = t.GetProperty(dataRecord.GetName(i));
LocalBuilder il_P = generator.DeclareLocal(typeof(PropertyInfo));
Label endIfLabel = generator.DefineLabel();
.... ...
Edit: all of this is basically what dapper does - but dapper is much more optimized. If I was writing this answer today, it would read simply: "use dapper".
If you aren't hugely "up" on IL, there are alternatives that get you the speed of IL and the convenience of reflection.
First example:
HyperDescriptor - uses a custom PropertyDescriptor
model that deals with the IL for you, so all you have is code like (plus the one-liner to enable HyperDescriptor
):
public static IEnumerable<T> Read<T>(IDataReader reader) where T : class, new()
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
PropertyDescriptor[] propArray = new PropertyDescriptor[reader.FieldCount];
for (int i = 0; i < propArray.Length; i++)
{
propArray[i] = props[reader.GetName(i)];
}
while(reader.Read()) {
T item = new T();
for (int i = 0; i < propArray.Length; i++)
{
object value = reader.IsDBNull(i) ? null : reader[i];
propArray[i].SetValue(item, value);
}
yield return item;
}
}
Second example:
LINQ expressions - quite lengthy, but I've discussed this (and the above, it turns out) on usenet - see this archive.