Are there any quick way to map some IDataReader to object without third party libraries such as AutoMapper or ValueInjecter?
2 Answers
Sure,
class MyObject
{
public string SomeProperty { get; set; }
public MyObject(IDataReader reader)
{
SomeProperty = reader.GetString(0);
// - or -
SomeProperty = reader.GetString(reader.GetOrdinal("SomeProperty"));
// etc.
}
}

- 14,171
- 3
- 41
- 68
-
I'm guessing that the downvote was given because the answer is obvious? @MSS didn't state that they had considered and rejected the obvious. Not only is this a valid answer, it is the answer I use in my own projects. I like the fact that it makes it explicit which objects participate in database serialization. – Tergiver Feb 24 '11 at 13:44
I'm not sure what you mean by quick, but you can put something together using reflection. There's a lot of assumptions you'll have to make, such as all your object's values are set via properties. And, your DataReader columns MUST match your object property name. But you could do something like this:
NOTE: The SetProperty
function is from an article on DevX. (It was in VB.NET, and I converted it to C# -- if there are mistakes, I probably missed something.)
IList<MyObject> myObjList = new List<MyObject>();
while (reader.Read()){
int fieldCount = reader.FieldCount;
MyObject myObj = new MyObject();
for(int i=0;i<fieldCount;i++){
SetProperty(myObj, reader.GetName(i), reader.GetOrdinal(i));
}
myObjList.Add(myObj);
}
bool SetProperty(object obj, String propertyName, object val) {
try {
//get a reference to the PropertyInfo, exit if no property with that
//name
System.Reflection.PropertyInfo pi = obj.GetType().GetProperty(propertyName);
if (pi == null) then return false;
//convert the value to the expected type
val = Convert.ChangeType(val, pi.PropertyType);
//attempt the assignment
pi.SetValue(obj, val, null);
return true;
}
catch {
return false;
}
}
No guarantees that this code will run (I'm just typing it and not compiling/testing it), but it at least may be a start.
I've done things like this in the past and have gotten fancy with applying attributes to my properties stating what data reader column to map to the property. Too much to include here, but this is just a starter and hopefully is what you're looking for.
Hope this helps!

- 28,421
- 8
- 67
- 102