全速加载中

C# DataTable转实体 通用方法

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

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

 

posted @ 2016-03-16 16:03  许鸿飞  阅读(282)  评论(0编辑  收藏  举报