通用的SqlDataReader到对象映射器

4
我将尝试构建一个通用的映射器,将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 的那行出现。

我已经尝试了所有方法,但我不知道可能出了什么问题。


数据库操作是有成本的。如果添加反射,它会明显变慢。更糟糕的是,你在循环内部这样做。你应该将反射部分移到循环外部,并最好依靠表达式树而不是反射。参见此答案作为示例。 - nawfal
相关链接:https://dev59.com/D0XXs4cB2Jgan1znzHjm,https://dev59.com/x3jZa4cB1Zd3GeqPjOC3,http://codereview.stackexchange.com/questions/58251/transform-datareader-to-listt-using-reflections - nawfal
@nawfal 你看过这篇帖子的日期了吗? - Mast
@Mast 是的。我的评论不再相关吗? - nawfal
2个回答

4

您正在尝试设置循环遍历的属性值,我认为您的意图是设置新创建的项目的值,因为它将与基于item.GetType()传递的Type匹配

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
@BrokenGlass 说得好,我修改了我的回答以确保他们看到。谢谢。 - CodeLikeBeaker

1

看起来这部分有问题:

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

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

然后变成:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接