I am trying to create a generic cardper that converts the results of 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, this works, but as soon as it tries to set the property value, I get the following error:
Object does not match target type
in the line where I have property.SetValue .
I tried everything and I don’t see what I can do wrong.
source share