/// <summary>
/// 实体转换辅助类
/// </summary>
public class ModelConvertHelper<T> where T : new()
{
/// <summary>
/// List泛型转换DataTable.
/// </summary>
public DataTable ListToDataTable<T>(List<T> items)
{
var tb = new DataTable(typeof(T).Name); PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in props)
{
Type t = GetCoreType(prop.PropertyType);
tb.Columns.Add(prop.Name, t);
} foreach (T item in items)
{
var values = new object[props.Length]; for (int i = ; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
} tb.Rows.Add(values);
} return tb;
} /// <summary>
/// model转换DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <returns></returns>
public DataTable ModelToDataTable<T>(T items)
{
var tb = new DataTable(typeof(T).Name); PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in props)
{
Type t = GetCoreType(prop.PropertyType);
tb.Columns.Add(prop.Name, t);
} var values = new object[props.Length]; for (int i = ; i < props.Length; i++)
{
values[i] = props[i].GetValue(items, null);
} tb.Rows.Add(values); return tb;
} /// <summary>
/// Determine of specified type is nullable
/// </summary>
public static bool IsNullable(Type t)
{
return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
} /// <summary>
/// Return underlying type if type is Nullable otherwise return the type
/// </summary>
public static Type GetCoreType(Type t)
{
if (t != null && IsNullable(t))
{
if (!t.IsValueType)
{
return t;
}
else
{
return Nullable.GetUnderlyingType(t);
}
}
else
{
return t;
}
} /// <summary>
/// DataTable转换泛型List
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static List<T> DataTableToList(DataTable dt)
{
// 定义集合
List<T> ts = new List<T>(); // 获得此模型的类型
Type type = typeof(T);
string tempName = "";
foreach (DataRow dr in dt.Rows)
{
T t = new T();
// 获得此模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name; // 检查DataTable是否包含此列 if (dt.Columns.Contains(tempName))
{
// 判断此属性是否有Setter
if (!pi.CanWrite) continue; object value = dr[tempName];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
ts.Add(t);
}
return ts;
} public static T DataTableToModel(DataTable dt)
{
// 定义实体
T t = new T(); // 获得此模型的类型
Type type = typeof(T);
string tempName = ""; foreach (DataRow dr in dt.Rows)
{ // 获得此模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name; // 检查DataTable是否包含此列 if (dt.Columns.Contains(tempName))
{
// 判断此属性是否有Setter
if (!pi.CanWrite) continue; object value = dr[tempName];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
break;
}
return t;
}
}

C#DataTable与Model互转的更多相关文章

  1. DataTable转换为Model实体对象

    记得在学校的时候,接触得最多的就是SqlHelper,每次在读取的时候不管是DataTable还是DataReader转换为实体对象的时候是最恼火的,因为要写很多代码,而且没有什么意义.后面接触到了反 ...

  2. DataTable转List,DataTable转为Model对象帮助类

    DataTable转List,DataTable转为Model对象帮助类 public class ModelConvertHelper<T> where T : new() { publ ...

  3. json,DataTable,model

    1.DataTable转json public class DataTableConvertJson { #region dataTable转换成Json格式 /// <summary> ...

  4. datatable 和实体互转

    public static class ModelConvertHelper<T> where T : class,new() { public static List<T> ...

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

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

  6. C#把 DataTable转换为Model实体

    public static List<T> GetModelFromDB<T>( DataTable dt ) { List<T> data = new List& ...

  7. 内裤:DataTable转Model

    public class ConvertHelper<T> where T : new() { /// <summary> /// 利用反射和泛型 /// </summa ...

  8. DataSet,DataTable,XML格式互转

    //// <summary> /// 将DataTable对象转换成XML字符串 /// </summary> /// <param name="dt" ...

  9. DataTable和List互转

    /// <summary> /// list转datatable /// </summary> /// <typeparam name="T"> ...

随机推荐

  1. SQL之DML

    DML(Data Manipulation Language)数据操纵语言statements are used for managing data within schema objects. 由D ...

  2. C#向服务器上传文件问题

    最近在写服务器端web上传的接口.但一直报错,上传不上去,后来发现是在分隔符中出现的问题. 错误的写法: var boundary = "---------------" + Da ...

  3. wp7启动+幻灯片效果

    using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Wi ...

  4. EF 完成指定数据迁移

    Update-Database -ConfigurationTypeName Bmw.Services.DealerService.WebApiHost.MigrationsOfDealerDB.De ...

  5. WinForm中DataGridView的使用(三) - 各种事件

    CellMouseDown/CellMouseUp 可获得行.列号 可用if (rowIndex >= 0 && e.Y > 4 && e.Y < ( ...

  6. 基于verilog的FFT算法8点12位硬件实现

    FFT算法8点12位硬件实现 (verilog) 1 一.功能描述: 1 二.设计结构: 2 三.设计模块介绍 3 1.蝶形运算(第一级) 3 2.矢量角度旋转(W) 4 3.CORDIC 结果处理 ...

  7. oracle 新增主键

    alter table tablename add constraint pk_tablename primary key (column1,column2,...); 可以新增单主键或联合主键: 新 ...

  8. nginx理解与配置

    准备: http服务器:①tomcat②apache③nginx(c语言开发) 文件系统:①mgfs ②mgbd:存储小文件 ③fastDFS:存储大文件.小文件,分布式文件系统 nginx是一种ht ...

  9. OC 术语表

    术语表 本附录包含了很多会用到的非正式定义术语.有些术语与Obective-C语言有关,其他术语则有自己的语源,来自面向对象程序设计的规范.在后一种情况中,术语的含义只有明确应用于Obective-C ...

  10. 洛谷P4015 运输问题(费用流)

    传送门 源点向仓库连费用$0$,流量为储量的边,商店向汇点连费用$0$,流量为需求的边,然后仓库向商店连流量$inf$,费用对应的边,跑个费用流即可 //minamoto #include<io ...