• 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;
    }

  • 相关阅读:
    umask
    mysql 错误总结 和FROM_UNIXTIME用法
    php 读取和下载execl
    Yii 2 load() 和 save()
    iframe 模拟ajax文件上传and formdata ajax 文件上传
    angular.js简单入门。
    mysql 慢日志
    mysql 基本操作 alter
    shell cut 用法
    微信支付与支付宝支付
  • 原文地址:https://www.cnblogs.com/guzhengtao/p/20180706_1556.html
Copyright © 2020-2023  润新知