DataTable转化成实体对象
/// <summary>
/// The data extension.
/// </summary>
public static class DataExtension
{
/// <summary>
/// ToList
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="reader">reader</param>
/// <returns>T</returns>
public static List<T> ToList<T>(this IDataReader reader) where T : class, new()
{
var result = new List<T>(); DataTable dt = reader.GetSchemaTable();
try
{
while (reader.Read())
{
var t = new T(); if (dt != null)
{
foreach (DataRow dr in dt.Rows)
{
// 当前列名&属性名
string columnName = dr[].ToString();
PropertyInfo pro = typeof(T).GetProperty(columnName); if (pro == null)
{
continue;
} if (!pro.CanWrite)
{
continue;
} pro.SetValue(t, ConvertExtension.ConvertHelper(reader[columnName], pro.PropertyType), null);
}
} result.Add(t);
}
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
if (!reader.IsClosed)
{
reader.Dispose();
reader.Close();
}
} return result;
} /// <summary>
/// ToList
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="dt">dt</param>
/// <returns>T</returns>
public static List<T> ToList<T>(this DataTable dt) where T : class, new()
{
var result = new List<T>();
foreach (DataRow dr in dt.Rows)
{
var t = new T();
try
{
foreach (DataColumn column in dt.Columns)
{
// 当前列名&属性名
string columnName = column.ColumnName;
PropertyInfo pro = typeof(T).GetProperty(columnName); if (pro == null)
{
continue;
} if (!pro.CanWrite)
{
continue;
} pro.SetValue(t, ConvertExtension.ConvertHelper(dr[columnName], pro.PropertyType), null);
}
}
catch (System.Exception ex)
{
throw ex;
} result.Add(t);
} return result;
} /// <summary>
/// ToList
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="ds">ds</param>
/// <returns>T</returns>
public static List<T> ToList<T>(this DataSet ds) where T : class, new()
{
return ds.Tables[].ToList<T>();
} /// <summary>
/// ToList
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="ds">ds</param>
/// <param name="dataTableIndex">dataTableIndex</param>
/// <returns>T</returns>
public static List<T> ToList<T>(this DataSet ds, int dataTableIndex) where T : class, new()
{
return ds.Tables[dataTableIndex].ToList<T>();
} /// <summary>
/// ToModel
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="reader">reader</param>
/// <returns>T</returns>
public static T ToModel<T>(this IDataReader reader) where T : class, new()
{
var t = new T();
DataTable dt = reader.GetSchemaTable();
try
{
while (reader.Read())
{
if (dt != null)
{
foreach (DataRow dr in dt.Rows)
{
// 当前列名&属性名
string columnName = dr[].ToString();
PropertyInfo pro = typeof(T).GetProperty(columnName); if (pro == null)
{
continue;
} if (!pro.CanWrite)
{
continue;
} pro.SetValue(t, ConvertExtension.ConvertHelper(reader[columnName], pro.PropertyType), null);
}
}
}
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
if (!reader.IsClosed)
{
reader.Dispose();
reader.Close();
}
} return t;
} /// <summary>
/// ToModel
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="dt">dt</param>
/// <returns>T</returns>
public static T ToModel<T>(this DataTable dt) where T : class, new()
{
var t = new T();
if (dt.Rows.Count <= )
{
return t;
} try
{
foreach (DataColumn column in dt.Columns)
{
// 当前列名&属性名
string columnName = column.ColumnName;
PropertyInfo pro = typeof(T).GetProperty(columnName);
if (pro == null)
{
continue;
} if (!pro.CanWrite)
{
continue;
} pro.SetValue(t, ConvertExtension.ConvertHelper(dt.Rows[][columnName], pro.PropertyType), null);
}
}
catch (System.Exception ex)
{
throw ex;
} return t;
} /// <summary>
/// ToModel
/// </summary>
/// <typeparam name="T">T</typeparam>
/// <param name="ds">ds</param>
/// <param name="dataTableIndex">dataTableIndex</param>
/// <returns>T</returns>
public static T ToModel<T>(this DataSet ds, int dataTableIndex = ) where T : class, new()
{
return ds.Tables[].ToModel<T>();
}
}
DataExtension
/// <summary>
/// The convert extension.
/// </summary>
public static class ConvertExtension
{
/// <summary>
/// The convert helper.
/// </summary>
/// <param name="value">
/// The value.
/// </param>
/// <param name="conversionType">
/// The conversion type.
/// </param>
/// <returns>
/// The <see cref="object"/>.
/// </returns>
public static object ConvertHelper(object value, Type conversionType)
{
Type nullableType = Nullable.GetUnderlyingType(conversionType); // 判断当前类型是否可为 null
if (nullableType != null)
{
if (value == DBNull.Value)
{
return null;
} // 若是枚举 则先转换为枚举
if (nullableType.IsEnum)
{
value = System.Enum.Parse(nullableType, value.ToString());
} return Convert.ChangeType(value, nullableType);
} if (conversionType.IsEnum)
{
return System.Enum.Parse(conversionType, value.ToString());
} return Convert.ChangeType(value, conversionType);
} /// <summary>
/// The convert to decimal null.
/// </summary>
/// <param name="targetObj">
/// The target obj.
/// </param>
/// <returns>
/// The <see cref="decimal"/>.
/// </returns>
public static decimal? ConvertToDecimalNull(object targetObj)
{
if (targetObj == null || targetObj == DBNull.Value)
{
return null;
} return Convert.ToDecimal(targetObj);
} /// <summary>
/// The convert to int null.
/// </summary>
/// <param name="targetObj">
/// The target obj.
/// </param>
/// <returns>
/// The <see cref="int"/>.
/// </returns>
public static int? ConvertToIntNull(object targetObj)
{
if (targetObj == null || targetObj == DBNull.Value)
{
return null;
} return Convert.ToInt32(targetObj);
} /// <summary>
/// The convert to string.
/// </summary>
/// <param name="obj">
/// The obj.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
public static string ConvertToString(object obj)
{
return obj == null ? string.Empty : obj.ToString();
} /// <summary>
/// 将泛类型集合List类转换成DataTable
/// </summary>
/// <param name="entitys">泛类型集合</param>
/// <typeparam name="T">T</typeparam>
/// <returns>DataTable</returns>
public static DataTable ListToDataTable<T>(List<T> entitys)
{
// 检查实体集合不能为空
if (entitys == null || entitys.Count < )
{
throw new System.Exception("需转换的集合为空");
} // 取出第一个实体的所有Propertie
Type entityType = entitys[].GetType();
PropertyInfo[] entityProperties = entityType.GetProperties(); // 生成DataTable的structure
// 生产代码中,应将生成的DataTable结构Cache起来,此处略
DataTable dt = new DataTable();
foreach (PropertyInfo t in entityProperties)
{
// dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
dt.Columns.Add(t.Name);
} // 将所有entity添加到DataTable中
foreach (object entity in entitys)
{
// 检查所有的的实体都为同一类型
if (entity.GetType() != entityType)
{
throw new System.Exception("要转换的集合元素类型不一致");
} object[] entityValues = new object[entityProperties.Length];
for (int i = ; i < entityProperties.Length; i++)
{
entityValues[i] = entityProperties[i].GetValue(entity, null);
} dt.Rows.Add(entityValues);
} return dt;
} /// <summary>
/// 转换中文星期
/// </summary>
/// <param name="dt">The dt.</param>
/// <returns>Week.</returns>
public static Week ConverToWeekByZHCN(this DateTime dt)
{
return (Week)dt.DayOfWeek;
} /// <summary>
/// 四舍五入保留2位小数(中国式)
/// </summary>
/// <param name="d"></param>
/// <returns></returns>
public static decimal DecimalTwoPlaces(this decimal d)
{
return Math.Round(d, , MidpointRounding.AwayFromZero);
}
}
ConvertExtension
将 IDataReader DataSet DataTable 转化成 List<T> Or T类型
上面是转化代码
DataTable转化成实体对象的更多相关文章
- DataTable转换为Model实体对象
记得在学校的时候,接触得最多的就是SqlHelper,每次在读取的时候不管是DataTable还是DataReader转换为实体对象的时候是最恼火的,因为要写很多代码,而且没有什么意义.后面接触到了反 ...
- 简单的反射 把datatable 转换成list对象
/// <summary> /// 把datatable 转换成list对象 /// </summary> /// <typeparam name="T&quo ...
- C# DataTable转换成实体列表 与 实体列表转换成DataTable
/// <summary> /// DataTable转换成实体列表 /// </summary> /// <typeparam name="T"&g ...
- DataTable转换成实体
public static class DataTableToEntity { /// <summary> /// 将DataTable数据源转换成实体类 /// </summary ...
- XML中的非法字符转化成实体
问题 如果XML有非法字符比如 "·",或者HTML标签<br/>.XML在解析的过程中就会出错.就无法正常解析,或者把xml反射成实体. 有些字符,像(<)这类 ...
- DataTable转成实体列表 和 DataRow转成实体类
#region DataTale转为实体列表 /// <summary> /// DataTale转为实体列表 /// </summary> /// <typeparam ...
- json数据转化成实体 存到数据库.
直接看步骤吧 1.一般我们会调用别人给的webservice获取一个字符串数据.如果为String data="xxxxxxxxxx"; 这个data事实上就是样例Enterpr ...
- C#把 DataTable转换为Model实体
public static List<T> GetModelFromDB<T>( DataTable dt ) { List<T> data = new List& ...
- DataTable 转换成 Json的3种方法
在web开发中,我们可能会有这样的需求,为了便于前台的JS的处理,我们需要将查询出的数据源格式比如:List<T>.DataTable转换为Json格式.特别在使用Extjs框架的时候,A ...
随机推荐
- Fiddler抓包域名过滤
Fiddler抓包域名过滤 我们在用Fiddler抓包的时候会抓到很多不需要的数据包,我们怎样才能过滤掉不想要的域名只显示自己想要的域名? 通过Fiddler域名过滤可以解决这一问题! 下面是只显示想 ...
- Selenium Webdriver——操作隐藏的元素(三)switchTo().frame()
在web 应用中经常会遇到frame 嵌套页面的应用,页WebDriver 每次只能在一个页面上识别元素,对于frame 嵌套内的页面上的元素,直接定位是定位是定位不到的.这个时候就需要通过switc ...
- Django-form组件和ModelForm组件
一. 构建Form表单 通过建一个类,添加需要进行验证的form字段,继而添加验证条件 from django import forms from django.forms import widget ...
- JQuery Form AjaxSubmit(options)在Asp.net中的应用注意事项
所需引用的JS: 在http://www.malsup.com/jquery/form/#download 下载:http://malsup.github.com/jquery.form.js 在ht ...
- Servlet—基础
什么是Servlet? 1 . jsp经编译后就变成了Servlet.(JSP的本质就是Servlet,JVM只能识别java的类,不能识别JSP的代 码,Web容器将JSP的代码编译成JVM能够识别 ...
- requirejs初体验
1.引入requirejs <script type="text/javascript" src="/js/common/require2.3.5.js" ...
- isKindOfClass和isMemberOfClass 的区别
判断对象类型 -(BOOL) isKindOfClass: classObj判断是否是这个类或者这个类的子类的实例 -(BOOL) isMemberOfClass: classObj 判断是否是这个类 ...
- nodejs中req.body对请求参数的解析问题
首先,先了解一下关于http协议里定义的四种常见数据的post方法,分别是: application/www-form-ulrencoded multipart/form-data applicati ...
- Linux基础命令---bzcat
bzcat 解压缩被bzip2压缩过的文件,将文件解压到标准输出,此命令只有一个选项-s.该指令对压缩过的二进制文件没有意义,因为二进制文件没有可读性. 此命令的适用范围:RedHat.RHEL.Ub ...
- API和正则表达式
第一章 String & StringBuilderString类用类final修饰,不能被继承,String字符串被创建后永远无法被改变,但字符串引用可以重新赋值,改变引用的指向java字符 ...