【发布时间】:2011-11-15 19:31:27
【问题描述】:
我正在尝试构建一个通用映射器,它将 SqlDataReader 的结果转换为类对象。
这是我的代码的基本结构:
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);
}
}
在大多数情况下它似乎可以工作,但是一旦它尝试设置属性的值,我就会收到以下错误:
对象与目标类型不匹配
在我有property.SetValue的那一行。
我已经尝试了所有方法,但我看不出我做错了什么。
【问题讨论】:
-
数据库操作是有代价的。添加反射,它会明显变慢。更糟糕的是,您在循环内执行此操作。您应该将反射部分移到循环之外,并且最好依赖表达式树而不是反射。例如,请参阅this answer
-
@nawfal 你看过这个发布的日期了吗?
-
@Mast 是的。我的 cmets 不再相关了吗?
标签: c# generics sqldatareader