I'm trying to build a generic mapper which will convert the results of a SqlDataReader into a class object.
Here is the basic structure for my code:
public interface IObjectCore
{
//contains properties for each of my objects
}
public class ObjectMapper<T> where T : IObjectCore, new()
{
public List<T> MapReaderToObjectList(SqlDataReader reader)
{
var resultList = new List<T>();
while (reader.Read())
{
var item = new T();
Type t = item.GetType();
foreach (PropertyInfo property in t.GetProperties())
{
Type type = property.PropertyType;
string readerValue = string.Empty;
if (reader[property.Name] != DBNull.Value)
{
readerValue = reader[property.Name].ToString();
}
if (!string.IsNullOrEmpty(readerValue))
{
property.SetValue(property, readerValue.To(type), null);
}
}
}
return resultList;
}
}
public static class TypeCaster
{
public static object To(this string value, Type t)
{
return Convert.ChangeType(value, t);
}
}
For the most part it seems to work, but as soon as it tries to set the value of the property, I get the following error:
Object does not match target type
on the line where I have property.SetValue
.
I have tried everything and I don't see what I might be doing wrong.