我想構建一個通用映射器,它將SqlDataReader的結果轉換爲類對象。通用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);
}
}
對於它似乎工作的大部分,但只要它試圖設置屬性的值,我收到以下錯誤:
Object does not match target type
就行了,我有property.SetValue
。
我已經試過了所有的東西,但我沒有看到我可能會做錯什麼。
Db的行動是有代價的。向它添加反射,它會明顯變慢。更糟糕的是,你在循環內部做到了這一點。您**應該**將反射部分移到循環外部,並且最好依賴表達式樹而不是反射。參見[這個答案](http://stackoverflow.com/questions/19841120/listt-property-binding-to-dbdatareader-issue/19845980#19845980)。 – nawfal
相關:http://stackoverflow.com/questions/812034/fastest-way-to-use-reflection-for-converting-datareader-to-list,http://stackoverflow.com/questions/19841120/generic-dbdatareader -to-listt-mapping,http://codereview.stackexchange.com/questions/58251/transform-datareader-to-listt-using-reflections – nawfal
@nawfal你看過這張貼的日期嗎? – Mast