datatable 和实体互转
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 和实体互转的更多相关文章
- List实体类、DataTable与xml互转
序列化常用Attribute讲解说明 [XmlRootAttribute("MyCity", Namespace="abc.abc", IsNullable=f ...
- 自用的基于Emit的C#下DataTable转实体类方法
之前一直在做WebForm的开发,数据绑定时直接DataTable绑定Gridview很方便,但是最近开始往MVC转,数据列表的传递和页面展示基本上是以List为主,像下面这样,遍历实体类的各个字段去 ...
- DataTable与实体类互相转换
/// <summary> /// DataTable与实体类互相转换 /// </summary> /// <typeparam name="T"& ...
- .net 根据匿名类生成实体类,根据datatable生成实体类,根据sql生成实体类
在开发中可能会遇到这几种情况 1.EF或LINQ查询出来的匿名对象在其它地方调用不方便,又懒的手动建实体类 2.通过datatable反射实体需要先建一个类 ,头痛 3.通过SQL语句返回的实体也需要 ...
- 三层架构中bll层把datatable转换为实体model的理解
看了很多人的项目,很多都是用到三层架构,其中BLL层中有一种将DataTable转换为实体的方法.一直没有明白为啥要这样做,今天特意去搜索了一下,如果没有答案我是准备提问,寻求解答了.还好找到一个相关 ...
- C#中DataTable与实体集合通用转换(使用扩展方法)
本案例提供了:把DataRow转换为单个实体.dataTable转换为List泛型支持时间格式转换. 下文的方法都是扩展方法.扩展方法要求写在静态类中,方法也要静态. 它必须在一个非嵌套.非泛型的静态 ...
- DataTable与实体类的转换
多年前写的DataTable与实体类的转换,已放github 阅读目录 介绍 起因 代码 UnitTest GitHub 介绍 很多年前一直使用Ado.net,后来慢慢转型到其他的orm,在转型过程中 ...
- DataTable 转实体
因为Linq的查询功能很强大,所以从数据库中拿到的数据为了处理方便,我都会转换成实体集合List<T>. 开始用的是硬编码的方式,好理解,但通用性极低,下面是控件台中的代码: using ...
- C# DataTable 转 实体类
C# 中查询结果DataTable转实体类: 比如:List<RtmInterview> rtmList = GetDataById( id); public List<RtmInt ...
随机推荐
- LeetCode.1030-曼哈顿距离排序矩阵单元格(Matrix Cells in Distance Order)
这是小川的第384次更新,第412篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第246题(顺位题号是1030).我们给出一个矩阵,其中R行和C列具有整数坐标(r,c)的 ...
- 通过U盘或CD/DVD装centos7,出现“dracut-initqueue timeout..."解决办法
1.在用CD/DVD挂载centos7镜像安装系统时,出现“dracut-initqueue timeout...", :/# cd dev :/# ls 2.这是因为安装程序未能找到安装文 ...
- 【洛谷p1058】立体图(已完结)
立体图[题目链接] 然后因为有点(不是有点,非常)懵,因此我只能看一步写一步. 首先总体思路: 将三维立体图看做二维平面图,先确定出二维图的长和宽,然后,按照三维立体图的透视顺序,从最后一排的最左开始 ...
- Codeforces Round #590 (Div. 3)(e、f待补
https://codeforces.com/contest/1234/problem/A A. Equalize Prices Again #include<bits/stdc++.h> ...
- 设备程序远程升级采用两种方式(优先采用IP方式)
设备程序远程升级采用两种方式(优先采用IP方式): 采用应急广播TS流传输技术规范的消息内容表携带升级包数据.当辅助数据类型值为44时,消息内容表传输的数据为程序升级包. 采用IP方式传输升级包数据. ...
- ArcGIS 在VS2010中 ESRI.ArcGIS.SOESupport.dll 无法正常加载的处理
转自 http://blog.csdn.net/tnt123688/article/details/23186973 问题描述: 打开ArcGIS的SOE模板后,提示 错误 命名空间“ESRI.A ...
- wex5 如何使用蓝牙 ble
使用蓝牙插件 需要在js中添加 require("cordova!cordova-plugin-ble-central"); ble插件具体文档: http://docs.we ...
- splice方法
此方法有三种用法: 第一种: 删除功能 返回删除内容 索引从0开始 var arr = [1,2,3,4]; var arr2 = arr.splice(0,2); arr2 ===> [1, ...
- 纯CSS绘制3D立方体
本篇记录的是使用CSS3绘制3D立方体,并旋转起来. 我的思路: 1️⃣ 首先,用div元素画6个正方形摞在一起放在画布中间.为了区分,分别给每个div选择了不同的颜色,并且设置为半透明方便透视. 2 ...
- MATLAB中产生高斯白噪声的两个函数
MATLAB中产生高斯白噪声非常方便,可以直接应用两个函数,一个是WGN,另一个是AWGN.WGN用于产生高斯白噪声,AWGN则用于在某一信号中加入高斯白噪声.1.WGN:产生高斯白噪声 y = wg ...