簡體   English   中英

通用SqlDataReader到Object Mapper

[英]Generic SqlDataReader to Object Mapper

我正在嘗試構建一個通用映射器,它將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的行。

我已經嘗試了一切,但我沒有看到我可能做錯了什么。

您正在嘗試設置要循環的屬性的值,我認為您的目的是設置新創建的項目的值,因為它將基於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);

看起來這部分是錯的:

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

您確定要通過將property傳遞給它來應用SetValue嗎? 在我看來你應該傳遞T類型的對象,它是item

然后變成:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM