zoukankan      html  css  js  c++  java
  • 使用特性将数据库返回的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();
    

      

  • 相关阅读:
    应用服务器安装
    datasnap的线程池
    压缩OLEVARIANT数据
    服务端日志记录
    提交主从表的多个已经修改的数据
    MySQL与PostgreSQL相比哪个更好?
    Vue入门常用指令详解
    Laravel模型事件的实现原理详解
    Git 遇到了 early EOF indexpack failed 问题
    Laravel 代码开发最佳实践
  • 原文地址:https://www.cnblogs.com/tony-brook/p/10484036.html
Copyright © 2011-2022 走看看