public static class ModelConvertHelper<T> where T : class,new()
{
public static List<T> DataTableToModel(DataTable table)
{
List<T> ts = new List<T>();

foreach (DataRow dr in table.Rows)
{
T t = new T();
// 获得此模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
var tempName = pi.Name;
if (table.Columns.Contains(tempName))
{
// 判断此属性是否有Setter
if (!pi.CanWrite) continue;

object value = dr[tempName];
if (value != DBNull.Value)
{
pi.SetValue(t, value, null);
}
else
{
switch (pi.PropertyType.ToString())
{
case "System.Decimal": pi.SetValue(t, 0, null);
break;
case "System.DataTime": pi.SetValue(t, "1900/7/2", null);
break;
case "System.String": pi.SetValue(t, "", null);
break;
default: pi.SetValue(t, 0, null);
break;
}

}

}
}
ts.Add(t);
}
return ts;
}

/// <summary>
/// DataTableToEntityList
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> DataTableToEntityList(DataTable dt)
{
List<T> entiyList = new List<T>();

Type entityType = typeof(T);
PropertyInfo[] entityProperties = entityType.GetProperties();
try
{
foreach (DataRow row in dt.Rows)
{
T entity = Activator.CreateInstance<T>();

foreach (PropertyInfo propInfo in entityProperties)
{
if (dt.Columns.Contains(propInfo.Name))
{
if (!row.IsNull(propInfo.Name))
{
if ((propInfo.PropertyType.Name == "Nullable`1") && (propInfo.PropertyType.FullName.Contains("System.DateTime")))
{
propInfo.SetValue(entity, Convert.ChangeType(row[propInfo.Name], typeof(DateTime)), null);
}
else if ((propInfo.PropertyType.Name == "Nullable`1") && (propInfo.PropertyType.FullName.Contains("System.Guid")))
{
propInfo.SetValue(entity, Convert.ChangeType(row[propInfo.Name], typeof(Guid)), null);
}
else if (propInfo.PropertyType.FullName.Contains("System.Decimal"))
{
if (row[propInfo.Name] != DBNull.Value && row[propInfo.Name].ToString() != "")
{
propInfo.SetValue(entity, Convert.ChangeType(row[propInfo.Name], typeof(decimal)), null);
}
else
{
propInfo.SetValue(entity, Decimal.Parse("0"));
}
}
else
{
propInfo.SetValue(entity, Convert.ChangeType(row[propInfo.Name], propInfo.PropertyType), null);
}
}
else
{
if (propInfo.PropertyType.FullName.Contains("System.String"))
{
propInfo.SetValue(entity, "");
}
}
}
}

entiyList.Add(entity);
}
}
catch (Exception ex)
{
string a = ex.Message.ToString();
throw ex;
}

return entiyList;
}

public static List<T> DataTableToEntityListIgnoreType(DataTable dt)
{
List<T> entiyList = new List<T>();

Type entityType = typeof(T);
PropertyInfo[] entityProperties = entityType.GetProperties();
try
{
foreach (DataRow row in dt.Rows)
{
T entity = Activator.CreateInstance<T>();

foreach (PropertyInfo propInfo in entityProperties)
{
if (dt.Columns.Contains(propInfo.Name))
{
if (!row.IsNull(propInfo.Name))
{
propInfo.SetValue(entity, row[propInfo.Name], null);
}
else
{
if (propInfo.PropertyType.FullName.Contains("System.String"))
{
propInfo.SetValue(entity, "");
}
}
}
}

entiyList.Add(entity);
}
}
catch (Exception ex)
{
throw ex;
}

return entiyList;
}

/// <summary>
/// datatable => model
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static T DataTableToEntity(DataTable dt)
{
try
{
if (dt.Rows.Count <= 0) return default(T);
DataRow row = dt.Rows[0];

T entity = Activator.CreateInstance<T>();
Type entityType = typeof(T);
PropertyInfo[] entityProperties = entityType.GetProperties();

foreach (PropertyInfo propInfo in entityProperties)
{
if (dt.Columns.Contains(propInfo.Name))
{
if (!row.IsNull(propInfo.Name))
{
if ((propInfo.PropertyType.Name == "Nullable`1") && (propInfo.PropertyType.FullName.Contains("System.DateTime")))
{
propInfo.SetValue(entity, Convert.ChangeType(row[propInfo.Name], typeof(DateTime)), null);
}
else if ((propInfo.PropertyType.Name == "Nullable`1") && (propInfo.PropertyType.FullName.Contains("System.Guid")))
{
propInfo.SetValue(entity, Convert.ChangeType(row[propInfo.Name], typeof(Guid)), null);
}
else if (propInfo.PropertyType.FullName.Contains("System.Decimal"))
{
propInfo.SetValue(entity, Convert.ChangeType(row[propInfo.Name], typeof(decimal)), null);
}
else
{
propInfo.SetValue(entity, Convert.ChangeType(row[propInfo.Name], propInfo.PropertyType), null);
}
}
}
else if (propInfo.PropertyType.Name == "String")
{
propInfo.SetValue(entity, string.Empty, null);
}
}
return entity;
}
catch (Exception ex)
{
throw ex;
}
}

#region 实体转换成DataTable
public static DataTable ModelConvertToTable(List<T> list)
{
T obj = list[0];
PropertyInfo[] propertys = obj.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
DataTable table = new DataTable();
foreach (var property in propertys)
{
table.Columns.Add(property.Name);
}
foreach (T item in list)
{
DataRow row = table.NewRow();
foreach (var property in propertys)
{
if (table.Columns.Contains(property.Name))
{
row[property.Name] = property.GetValue(item, null) == null ? DBNull.Value : property.GetValue(item, null);
}
}
table.Rows.Add(row);
}
return table;
}

static List<Type> _bascType = new List<Type>() {
typeof(System.String),
typeof(System.Decimal),
typeof(System.Boolean),
typeof(System.Char),
typeof(System.Byte),
typeof(System.SByte),
typeof(System.Int16),
typeof(System.Int32),
typeof(System.Int64),
typeof(System.UInt16),
typeof(System.UInt32),
typeof(System.UInt64),
typeof(System.Single),
typeof(System.Double),
typeof(System.DateTime)

};

public static DataTable EntityToDataTableV2(List<T> entityList)
{
if (entityList == null || entityList.Count <= 0)
{
return null;
}
DataTable dt = new DataTable();
Type entityType = typeof(T);
PropertyInfo[] entityProperties = entityType.GetProperties();
Type colType = null;
foreach (PropertyInfo propInfo in entityProperties)
{
if (propInfo.PropertyType.IsGenericType)
{
colType = Nullable.GetUnderlyingType(propInfo.PropertyType);
}
else
{
colType = propInfo.PropertyType;
}
//if (colType.GetInterfaces().Contains(typeof(IComparable)))
if (_bascType.Contains(colType))
{
dt.Columns.Add(propInfo.Name, colType);
}
}
foreach (T entity in entityList)
{
DataRow newRow = dt.NewRow();
foreach (PropertyInfo propInfo in entityProperties)
{
if (dt.Columns.Contains(propInfo.Name))
{
object objValue = propInfo.GetValue(entity, null);
newRow[propInfo.Name] = objValue == null ? DBNull.Value : objValue;
}
}
dt.Rows.Add(newRow);
}
return dt;
}

public static DataTable EntityToDataTable(List<T> entityList)
{
if (entityList == null || entityList.Count <= 0)
{
return null;
}
DataTable dt = new DataTable();
Type entityType = typeof(T);
PropertyInfo[] entityProperties = entityType.GetProperties();
Type colType = null;
foreach (PropertyInfo propInfo in entityProperties)
{
if (propInfo.PropertyType.IsGenericType)
{
colType = Nullable.GetUnderlyingType(propInfo.PropertyType);
}
else
{
colType = propInfo.PropertyType;
}

if (colType.FullName.StartsWith("System"))
{
dt.Columns.Add(propInfo.Name, colType);
}
}
foreach (T entity in entityList)
{
DataRow newRow = dt.NewRow();
foreach (PropertyInfo propInfo in entityProperties)
{
if (dt.Columns.Contains(propInfo.Name))
{
object objValue = propInfo.GetValue(entity, null);
newRow[propInfo.Name] = objValue == null ? DBNull.Value : objValue;
}
}
dt.Rows.Add(newRow);
}
return dt;
}
#endregion
}

datatable 和实体互转的更多相关文章

  1. List实体类、DataTable与xml互转

    序列化常用Attribute讲解说明 [XmlRootAttribute("MyCity", Namespace="abc.abc", IsNullable=f ...

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

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

  3. DataTable与实体类互相转换

    /// <summary> /// DataTable与实体类互相转换 /// </summary> /// <typeparam name="T"& ...

  4. .net 根据匿名类生成实体类,根据datatable生成实体类,根据sql生成实体类

    在开发中可能会遇到这几种情况 1.EF或LINQ查询出来的匿名对象在其它地方调用不方便,又懒的手动建实体类 2.通过datatable反射实体需要先建一个类 ,头痛 3.通过SQL语句返回的实体也需要 ...

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

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

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

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

  7. DataTable与实体类的转换

    多年前写的DataTable与实体类的转换,已放github 阅读目录 介绍 起因 代码 UnitTest GitHub 介绍 很多年前一直使用Ado.net,后来慢慢转型到其他的orm,在转型过程中 ...

  8. DataTable 转实体

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

  9. C# DataTable 转 实体类

    C# 中查询结果DataTable转实体类: 比如:List<RtmInterview> rtmList = GetDataById( id); public List<RtmInt ...

随机推荐

  1. mysql 关键字大全

    mysql无论表名,还是字段名都应该避开mysql关键字. 如字段使用关键字,sql查询需加上` `.   查询插件,当使用关键字,会报错. usage

  2. 交换机安全学习笔记 第六章 IPV4 ARP攻击

    ARP欺骗攻击 常用工具:  dsniff(Linux/windows).ettercap(Linux/windows).cain(仅windows). ARP欺骗攻击的目的是嗅探发往某主机的所有IP ...

  3. Linux系统中使用Nignx配置反向代理负载均衡

    目录 使用nginx实现动静分离的负载均衡集群 使用nginx实现负载均衡和动静分离 使用nginx实现动静分离的负载均衡集群 Nginx官网源码包下载链接:http://nginx.org/en/d ...

  4. C++中函数模板的概念和意义

    1,对泛型编程进行学习,泛型编程是实际工程开发中必用的技术,大型公司的通用 库都是采用泛型编程的技术完成的,C++ 中支持泛型编程技术,C++ 中的函数  模板和类模板就是 C++ 中泛型编程技术,本 ...

  5. C++继承中的同名覆盖

    1,父子间的冲突是由继承带来的,两个类之间存在了继承的关系,必然的会带来一 些问题,本文要讨论的是父子之间成员变量或成员函数的命名问题: 2,思考: 1,子类中是否可以定义父类中的同名成员? 1,可以 ...

  6. Codeforces6E_Exposition

    题意 给定一个序列,求有多少个最长连续子序列满足最大值减最小值之差不超过\(k\). 分析 跟序列最大值最小值有关的可以想到单调栈,先预处理出每个数作为最大值能延伸的区间,然后枚举每个数作为最大值. ...

  7. Vue 系列(一): Vue + Echarts 开发可复用的柱形图组件

    目录 前置条件 安装echarts 引入echarts 柱形图组件开发 在何时初始化组件? 完整的代码 记得注册组件!!! 本文归柯三(kesan)所有,转载请注明出处 https://www.cnb ...

  8. Ubuntu安装openssh安装ssh、 免密登录、 创建新用户并免密登录

               一.安装openssh sudo apt-get install openssh-server ssh localhost 二.免密登录 cd ~/.ssh ssh-keygen ...

  9. java压缩文件中文名乱码问题

    import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; 改为 import org.apache.tools.zip. ...

  10. uni-app如何编写底部导航栏

    在pages.json中配置代码如下: { "pages": [ //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocat ...