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. 引入父目录模块 import

    a : a1.py a2.py b : b1.py 其中 a, b 同目录,现在想在b1中引用a1里面内容 在b1中需要进行进行如下操作 x = path.join('..') sys.path.ap ...

  2. Nginx_Ubuntu

    一. 基本步骤 1.1 环境准备 开始前,请确认gcc g++开发类库是否装好,默认已经安装. 注: 等待linux下载更新功能准备好了 重启系统 在执行下载安装命令,如执行命令没有问题可以继续往下走 ...

  3. Python笔记(二)

    python笔记 函数式编程 函数 函数是Python内建支持一种封装(将大段代码拆成函数) 通过函数的调用,可以将复制的任务分解. 函数式编程(Functional Programming) 计算机 ...

  4. python 链接mysql

    下载对应版本   安装 https://dev.mysql.com/downloads/connector/python/ 创建链接 # python 链接mysqlimport mysql.conn ...

  5. 搜索专题:Balloons

    搜索专题:Balloons 这道题一看与时间有关,第一想到的就是BFS,定义一个状态,包含每一个状态的剩余气球数,已经进行的时间和每一个志愿者上一次吹气球的时间: 每一次状态转换时,检查是否有没有使用 ...

  6. MD5算法+盐Salt

    1.MD算法的基的概念    MD5算法是典型的消息摘要算法,其前身有MD2.MD3和MD4算法,它由MD4.MD3和MD2算法改进而来.不论是哪一种MD算法,它们都需 要获得一个随机长度的信息并产生 ...

  7. webpack入门学习手记(一)

    本人微信公众号:前端修炼之路,欢迎关注. 之前用过gulp.grunt,但是一直没有学习过webpack.这两天刚好有时间,学习了下webpack.webpack要想深入研究,配置的东西比较多,网上的 ...

  8. 如何把maven文件pom.xml中的java包下载下来

    右击pom.xml文件,选择Run As-->Maven build- 在打开的页面中,如图输入"dependency:copy-dependencies",后点击" ...

  9. 可以提升幸福感的js小技巧(上)

    1. 类型强制转换 1.1 string强制转换为数字 可以用 *1来转化为数字(实际上是调用 .valueOf方法) 然后使用 Number.isNaN来判断是否为 NaN,或者使用 a!==a 来 ...

  10. js 学习四 对象应用 吃货游戏

    游戏来源于 Mdn学习网站: 该例子用于对象的理解非常有效(建议看完上面网站的内容在开始练习) 弹球 body { margin: 0; overflow: hidden; font-family: ...