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 ...
随机推荐
- Spring Gateway从入门到精通
1.Spring Gateway过滤器详解 2.Spring Gateway之Predicate详解 3.spring cloud gateway自定义过滤器 4.Spring Cloud Gatew ...
- 【Linux 网络编程】TCP/IP四层模型
应用层.传输层.网络层.链路层 链路层:常用协议 ARP(将物理地址转化为IP地址) RARP(将IP地址转换为物理地址) 网络层(IP层):重要协议ICMP IP IGMP 传输层:重要的协议TCP ...
- Css设置最优先
input{ width: 220px !important; } css中 加上 !important 用一些前端框架,源文件修改不便时 可以这样用
- go相关资料
1.go的调度2.go struct能不能比较 因为是强类型语言,所以不同类型的结构不能作比较,但是同一类型的实例值是可以比较的,实例不可以比较,因为是指针类型 3.go defer(for defe ...
- sql认识
DDL – Data Definition Language数据定义语言DML – Data Manipulation Language数据操作语言DCL – Data Control Languag ...
- HBASE学习笔记(四)
这两天把要前几天的知识点回顾一下,接下来我会用自己对知识点的理解来写一些东西 一.知识点回顾 1.hbase集群启动:$>start-hbase.sh ===>hbase-daemon.s ...
- css的样式问题
项目里面遇到一个布局: 然后侧边栏菜单的高度要随着内容的高度变化而变化:所以在这里贴一下代码:效果如下 <!DOCTYPE html> <html lang="en&quo ...
- vue-nuxt--切换布局文件
1.暂时没有找到服务器端渲染 非服务器端切换: window.$nuxt.setLayout('blog')
- WebView获取title更改
[self.titleLabel setText:[self.webVIew stringByEvaluatingJavaScriptFromString:@"document.title& ...
- java 可变长度参数列表
public class Main11 { public static void print(Integer... args){ if(args !=null) System.out.println( ...