public static T GetEntity<T>(DataTable table) where T : new()
    {
        T entity = new T();
        foreach (DataRow row in table.Rows)
        {
            foreach (var item in entity.GetType().GetProperties())
            {
                if (row.Table.Columns.Contains(item.Name))
                {
                    if (DBNull.Value != row[item.Name])
                    {
                        item.SetValue(entity, Convert.ChangeType(row[item.Name], item.PropertyType), null);
                    }

}
            }
        }

return entity;
    }

dataTable转化为实体列表MethodOne:

public static IList<T> GetEntities<T>(DataTable table) where T : new()
    {
        IList<T> entities = new List<T>();
        foreach (DataRow row in table.Rows)
        {
            T entity = new T();
            foreach (var item in entity.GetType().GetProperties())
            {
                item.SetValue(entity, Convert.ChangeType(row[item.Name], item.PropertyType), null);
            }
            entities.Add(entity);
        }
        return entities;
    }

MethodTwo:

/// <summary>
        /// DataTable 转化为对象集合
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<TEntity> ToList<TEntity>(DataTable dt) where TEntity : new()
        {
            List<TEntity> listEntity = new List<TEntity>();
            if (dt != null && dt.Rows.Count > 0)
            {
                int fieldCount = dt.Columns.Count;
                foreach (DataRow item in dt.Rows)
                {
                    TEntity t = (TEntity)Activator.CreateInstance(typeof(TEntity));

for (int i = 0; i < fieldCount; i++)
                    {
                        PropertyInfo field = t.GetType().GetProperty(dt.Columns[i].ColumnName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                        if (field != null)
                        {
                            if (item[i] == null || Convert.IsDBNull(item[i]))
                            {
                                field.SetValue(t, null, null);
                            }
                            else
                            {
                                field.SetValue(t, item[i], null);
                            }
                        }
                    }

listEntity.Add(t);
                }
            }
            if (listEntity.Count == 0)
            {
                return null;
            }

return listEntity;
        }

C# DataTable转实体 通用方法【转】的更多相关文章

  1. C# DataTable转实体通用方法

    public static class DataTableHelper { public static T GetEntity<T>(DataTable table) where T : ...

  2. C# DataTable转实体 通用方法

    public static T GetEntity<T>(DataTable table) where T : new() { T entity = new T(); foreach (D ...

  3. 三层架构中bll层把datatable转换为实体model的理解

    看了很多人的项目,很多都是用到三层架构,其中BLL层中有一种将DataTable转换为实体的方法.一直没有明白为啥要这样做,今天特意去搜索了一下,如果没有答案我是准备提问,寻求解答了.还好找到一个相关 ...

  4. 使用 AutoMapper 映射 IDataReader、DataSet、DataTable 到实体类

    AutoMapper是一个.NET的对象映射工具. 项目地址:https://github.com/AutoMapper/AutoMapper. 帮助文档:https://github.com/Aut ...

  5. C#中DataTable与实体集合通用转换(使用扩展方法)

    本案例提供了:把DataRow转换为单个实体.dataTable转换为List泛型支持时间格式转换. 下文的方法都是扩展方法.扩展方法要求写在静态类中,方法也要静态. 它必须在一个非嵌套.非泛型的静态 ...

  6. DataTable数据赋值给Model通用方法

    注:该文属本人原创,今后项目中发现该方法存在BUG会实时更新,转载记得附上原文出处,方便大家获得最新代码. 相信大家在做项目中,经常会根据不同的表new各种不同的Model,当需要对Model进行实例 ...

  7. datatable与实体类之间相互转化的几种方法

    #region DataTable转换成实体类 /// <summary> /// 填充对象列表:用DataSet的第一个表填充实体类 /// </summary> /// & ...

  8. DataTable 转实体

    因为Linq的查询功能很强大,所以从数据库中拿到的数据为了处理方便,我都会转换成实体集合List<T>. 开始用的是硬编码的方式,好理解,但通用性极低,下面是控件台中的代码: using ...

  9. 自用的基于Emit的C#下DataTable转实体类方法

    之前一直在做WebForm的开发,数据绑定时直接DataTable绑定Gridview很方便,但是最近开始往MVC转,数据列表的传递和页面展示基本上是以List为主,像下面这样,遍历实体类的各个字段去 ...

随机推荐

  1. Android实现ListView或GridView首行/尾行距离屏幕边缘距离

    直接上关键属性: 设置ListView或GridView的android:clipToPadding = true, 然后通过paddingTop和paddingBottom设置距离就好了.

  2. 在IE浏览器中iframe跨域访问cookie/session丢失的解决办法

    单点登录需要在需要进入的子系统B中添加一个类,用于接收A系统传过来的参数: @Action(value = "outerLogin", results = { @Result(na ...

  3. linux之SQL语句简明教程---CONCATENATE

    有的时候,我们有需要将由不同栏位获得的资料串连在一起.每一种资料库都有提供方法来达到这个目的: MySQL: CONCAT( ) Oracle: CONCAT( ), || SQL Server: + ...

  4. poj1581

    A Contesting Decision Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 2519   Accepted: ...

  5. wait函数返回值总结,孤儿进程与僵尸进程[总结]

    http://blog.csdn.net/astrotycoon/article/details/41172389 wait函数返回值总结 http://www.cnblogs.com/Anker/p ...

  6. ASP.NET 委托,异步调用例子 .

    简要介绍:1.定义异步执行需要调用的方法2.定义具有与异步执行方法相同签名的委托(Delegate):3.调用 BeginInvoke 和 EndInvoke 方法.   3.1. BeginInvo ...

  7. 查询本天气预报Web Services支持的国内外城市或地区信息

    原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://zhangkui.blog.51cto.com/1796259/497324 本文 ...

  8. 使用OAuth2.0访问豆瓣API

    如何计算某个用户的access_token过期时间?开发者可以通过两种方式计算:用户授权时,oauth2/access_token接口返回的expires_in值就是access_token的生命周期 ...

  9. 【单点更新,区间查询,线段树】【HDU1166】【敌兵布阵】

    线段树要捡回来学了 才知道以前抄的模板就是杭电传奇学长写的,写起来更有激情了: 一点注意: 单点更新完后记得pushup(),向上更新信息 以下是对线段树的理解 线段树的节点代表一段线段,节点编号没有 ...

  10. div+css中常见的浏览器兼容性处理-兼容不同浏览器

    在网站设计的时候,应该注意css样式兼容不同浏览器问题,特别是对完全使用DIV CSS设计的网,就应该更注意IE6 IE7 FF对CSS样式的兼容,不然,你的网乱可能出去不想出现的效果! div+cs ...