我正在尝试构建一个通用映射器,它将 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);

关于c# - 通用 SqlDataReader 到对象映射器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8142040/

10-13 05:57