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();
    

      

  • 相关阅读:
    kettle安装及初步使用
    Datax初步使用
    可修改性及其实现战术(hot words)
    淘宝网的六个质量属性
    python数据可视化笔记---——matplotlib.pyplot()
    Linux虚拟环境virtualevn
    deepin安装虚拟环境virtualenv
    python面试题-web后端
    rabbitmq和redis用作消息队列的区别
    nginx配置项概括说明
  • 原文地址:https://www.cnblogs.com/tony-brook/p/10484036.html
Copyright © 2011-2022 走看看