2011-02-23 45 views

回答

1

我不知道你快的意思,但你可以使用反射把東西在一起。你需要做很多假設,比如所有對象的值都是通過屬性設置的。而且,您的DataReader列必須與您的對象屬性名稱匹配。但是你可以這樣做:

注意:SetProperty函數來自DevX上的一篇文章。 (這是在VB.NET,我就轉換成C# - 如果有錯誤,我可能錯過了一些東西。)

IList<MyObject> myObjList = new List<MyObject>(); 

while (reader.Read()){ 
    int fieldCount = reader.FieldCount; 
    MyObject myObj = new MyObject(); 
    for(int i=0;i<fieldCount;i++){ 
    SetProperty(myObj, reader.GetName(i), reader.GetOrdinal(i)); 
    } 
    myObjList.Add(myObj); 
} 

bool SetProperty(object obj, String propertyName, object val) { 
    try { 
     //get a reference to the PropertyInfo, exit if no property with that 
     //name 
     System.Reflection.PropertyInfo pi = obj.GetType().GetProperty(propertyName); 
     if (pi == null) then return false; 
     //convert the value to the expected type 
     val = Convert.ChangeType(val, pi.PropertyType); 
     //attempt the assignment 
     pi.SetValue(obj, val, null); 
     return true; 
    } 
    catch { 
     return false; 
    } 
} 

不保證該代碼將運行(我只是打字它,而不是編譯/測試它),但它至少可能是一個開始。

我已經在過去做過這樣的事情,並且喜歡將屬性應用到我的屬性,聲明要映射到屬性的數據讀取器列。這裏包含太多的內容,但這只是一個啓動器,希望是你想要的。

希望這會有所幫助!

1

當然,

class MyObject 
{ 
    public string SomeProperty { get; set; } 
    public MyObject(IDataReader reader) 
    { 
     SomeProperty = reader.GetString(0); 
     // - or - 
     SomeProperty = reader.GetString(reader.GetOrdinal("SomeProperty")); 
     // etc. 
    } 
} 
+0

我猜測downvote是因爲答案明顯嗎? @MSS沒有說明他們已經考慮並拒絕了這個明顯的問題。這不僅是一個有效的答案,它是我在自己的項目中使用的答案。我喜歡這樣的事實,即它明確了哪些對象參與數據庫序列化。 – Tergiver 2011-02-24 13:44:11