zoukankan      html  css  js  c++  java
  • Table转换成实体、Table转换成实体集合(可转换成对象和值类型)

    /// <summary>
    /// Table转换成实体
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="table"></param>
    /// <returns></returns>
    public static T ToEntity<T>(this DataTable table) where T : class, new()
    {
    if (table == null || table.Rows == null || table.Rows.Count <= 0)
    {
    return default(T);
    }
    var entity = (T)Activator.CreateInstance(typeof(T));
    var row = table.Rows[0];
    var properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);

    foreach (var property in properties)
    {
    if (table.Columns.Contains(property.Name))
    {
    if (!IsNullOrDBNull(row[property.Name]))
    {
    property.SetValue(entity, HackType(row[property.Name], property.PropertyType), null);
    }
    }
    }
    return entity;
    }

    /// <summary>
    /// Table转换成实体集合(可转换成对象和值类型)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="table"></param>
    /// <returns></returns>
    public static List<T> ToList<T>(this DataTable table)
    {
    var list = new List<T>();
    var properties = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
    for (var i = 0; i < table.Rows.Count; i++)
    {
    var row = table.Rows[i];
    T entity;
    var tType = typeof(T);
    if (!(tType == typeof(string)) && (tType.IsClass || tType.IsGenericType))
    {
    entity = (T)Activator.CreateInstance(typeof(T));
    foreach (var property in properties)
    {
    if (table.Columns.Contains(property.Name))
    {
    if (!IsNullOrDBNull(row[property.Name]))
    {
    property.SetValue(entity, HackType(row[property.Name], property.PropertyType), null);
    }
    }
    }
    }
    else
    {
    //entity = default(T);
    entity = ConvertUtils.To(row[0], default(T));
    }
    list.Add(entity);
    }
    return list;
    }

  • 相关阅读:
    2016/11/10 kettle概述
    2016/11/07 线程的创建和启动
    python3 pip使用报错
    django建表报错
    django学习
    前端系列
    git使用标准
    我的Python之路
    nginx优化
    python安装包的时候报错
  • 原文地址:https://www.cnblogs.com/guzhengtao/p/20180706_1556.html
Copyright © 2011-2022 走看看