2011-11-15 38 views
4

我想構建一個通用映射器,它將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

我已經試過了所有的東西,但我沒有看到我可能會做錯什麼。

+0

Db的行動是有代價的。向它添加反射,它會明顯變慢。更糟糕的是,你在循環內部做到了這一點。您**應該**將反射部分移到循環外部,並且最好依賴表達式樹而不是反射。參見[這個答案](http://stackoverflow.com/questions/19841120/listt-property-binding-to-dbdatareader-issue/19845980#19845980)。 – nawfal

+0

相關: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

+0

@nawfal你看過這張貼的日期嗎? – Mast

回答

4

您正試圖設置您正在循環的屬性的值,我認爲您的意圖是設置新創建的項目的值,因爲這將與您基於的傳遞類型匹配在item.GetType()

var item = new T(); 
//other code 
property.SetValue(item , readerValue.To(type), null); 

,而不是

property.SetValue(property, readerValue.To(type), null); 

而且每評論,請確保您有:

resultList.Add(item); 
+1

也'resultList.Add(item);'後來丟失 – BrokenGlass

+0

@BrokenGlass好點,我修改了我的答案,以確保他們看到。謝謝。 – CodeLikeBeaker

+0

它工作完美,謝謝 – Wondercricket

1

看起來這部分是錯誤的:

property.SetValue(property, readerValue.To(type), null);

你想通過傳遞property將其申請的SetValue你確定? 在我看來,你應該通過類型T的對象是item

這則變爲:

property.SetValue(item, readerValue.To(type), null);