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

  • 相关阅读:
    413 Request Entity Too Large
    小米3手机上加载相册图片失败的问题
    MVC+Ninject+三层架构+代码生成 -- 总结(99)
    1)python 爬取小说
    102)微信小程序 van-dialog
    101) 微信小程序 input 双向绑定
    MVC 表格按树状形式显示 jstree jqgrid
    1. mvc 树形控件tree + 表格jqgrid 显示界面
    叫號系統
    HTML5 下拉控件绑定数据
  • 原文地址:https://www.cnblogs.com/guzhengtao/p/20180706_1556.html
Copyright © 2011-2022 走看看