【问题标题】:Generic SqlDataReader to Object Mapper通用 SqlDataReader 到对象映射器
【发布时间】: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的那一行。

我已经尝试了所有方法,但我看不出我做错了什么。

【问题讨论】:

标签: c# generics sqldatareader


【解决方案1】:

您正在尝试设置您正在循环的属性的值,我认为您的意图是设置您拥有的新创建项目的值,因为这将匹配您基于它传递的类型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);

【讨论】:

  • 之后resultList.Add(item); 也不见了
  • @BrokenGlass 好点,我修改了我的答案以确保他们看到这一点。谢谢。
【解决方案2】:

看起来这部分是错误的:

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

您确定要通过传递 property 来应用 SetValue 吗? 在我看来,您应该传递 T 类型的对象,即item

然后变成:

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

【讨论】:

    猜你喜欢
    • 2017-04-23
    • 2013-06-16
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    相关资源
    最近更新 更多