使用特性将数据库返回的datatable转换成对象列表

    public class ColumnMapAttribute : Attribute
    {
        private readonly string _name;
        public ColumnMapAttribute(string name)
        {
            _name = name;
        }
        public string Name { get { return _name; } }
    }

    public class DbModelBase
    {
        public DbModelBase()
        {
        }

        public DbModelBase(DataRow row)
        {
            foreach (var tuple in GetType().GetProperties().Select(p =>
            {
                object[] objs = p.GetCustomAttributes(typeof(ColumnMapAttribute), false);
                return new Tuple<PropertyInfo, string>(p, objs.Length > 0 ? ((ColumnMapAttribute)objs[0]).Name : null);
            }).Where(t => t.Item2 != null))
            {
                object value = row[tuple.Item2];
                if (value != DBNull.Value)
                {
                    Type type = tuple.Item1.PropertyType;
                    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                    {
                        //DateTime? -> DateTime
                        type = type.GetGenericArguments()[0];
                    }
                    object changedValue = Convert.ChangeType(value, type);
                    tuple.Item1.SetValue(this, changedValue, null);
                }
            }
        }
    }

  

public class PersonClass: DbModelBase
    {
        public PersonClass(DataRow row) : base(row) { }

        [ColumnMap("person_id")]
        public int PersonId { get; set; }

        [ColumnMap("name")]
        public string PersonName { get; set; }

    }

  //上面实现了一个自定义特性类,用于记录数据库字段名

  //使用 DbModelBase类做字段和属性之间的映射

  //使用时, 只需要继承DbModelBase 在属性上写上对应的字段名称

var resultModel = table.Rows.Cast<DataRow>().Select(row => new PersonClass(row));

  //使用上面这句话获取的数据使用起来很耗时(原因不明)

       //加上.ToList();就变快了

var resultModel = table.Rows.Cast<DataRow>().Select(row => new PersonClass(row)).ToList();

  

原文地址:https://www.cnblogs.com/tony-brook/p/10484036.html