/// <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转化成实体对象的更多相关文章

  1. DataTable转换为Model实体对象

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

  2. 简单的反射 把datatable 转换成list对象

    /// <summary> /// 把datatable 转换成list对象 /// </summary> /// <typeparam name="T&quo ...

  3. C# DataTable转换成实体列表 与 实体列表转换成DataTable

    /// <summary> /// DataTable转换成实体列表 /// </summary> /// <typeparam name="T"&g ...

  4. DataTable转换成实体

    public static class DataTableToEntity { /// <summary> /// 将DataTable数据源转换成实体类 /// </summary ...

  5. XML中的非法字符转化成实体

    问题 如果XML有非法字符比如 "·",或者HTML标签<br/>.XML在解析的过程中就会出错.就无法正常解析,或者把xml反射成实体. 有些字符,像(<)这类 ...

  6. DataTable转成实体列表 和 DataRow转成实体类

    #region DataTale转为实体列表 /// <summary> /// DataTale转为实体列表 /// </summary> /// <typeparam ...

  7. json数据转化成实体 存到数据库.

    直接看步骤吧 1.一般我们会调用别人给的webservice获取一个字符串数据.如果为String data="xxxxxxxxxx";  这个data事实上就是样例Enterpr ...

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

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

  9. DataTable 转换成 Json的3种方法

    在web开发中,我们可能会有这样的需求,为了便于前台的JS的处理,我们需要将查询出的数据源格式比如:List<T>.DataTable转换为Json格式.特别在使用Extjs框架的时候,A ...

随机推荐

  1. FireFox Plugin编程

    9 jiaofeng601, +479 9人支持,来自 Meteor.猪爪.hanyuxinting更多   本文通过多图组合,详细引导初学者开发NPAPI的浏览器插件. 如需测试开发完成的插件请参考 ...

  2. 评价指标的局限性、ROC曲线、余弦距离、A/B测试、模型评估的方法、超参数调优、过拟合与欠拟合

    1.评价指标的局限性 问题1 准确性的局限性 准确率是分类问题中最简单也是最直观的评价指标,但存在明显的缺陷.比如,当负样本占99%时,分类器把所有样本都预测为负样本也可以获得99%的准确率.所以,当 ...

  3. 【转】webpack中关于source map的配置

    Webpack中sourcemap的配置 sourcemap是为了解决开发代码与实际运行代码不一致时帮助我们debug到原始开发代码的技术.尤其是如今前端开发中大部分的代码都经过编译,打包等工程化转换 ...

  4. 021-centos6.5上二进制安装mysql5.7.22

    思路: 下载上传mysql的二进制安装包. 准备好mysql的用户.安装目录basedir.数据目录datadir.配置文件/etc/my.cnf. 初始化出数据库. 配置启动服务. 开机启动. 配置 ...

  5. python解决matplotlib中文坐标值乱码的问题

    加上这句话即可 plt.rcParams['font.sans-serif']=['SimHei'] 效果:

  6. 关于VS2010的帮助文档更改路径

    不小心把MSDN装在系统盘怎么办? 由于自己的C盘空间比较有限,所以经常需要把软件安装在其他磁盘,比如E盘,但是这次重装却不小心就装在C盘了,特遗憾,偶然在网上找到可以更改路径的方法,自己试试,成功了 ...

  7. Linux命令: 替换字符串

    敲命令按以下顺序 ①vim filename ②e ③i ④ESC 1    :s/str1/str2    把当前行的第一个str1替换成str2 2    :s/str1/str2/g    把当 ...

  8. 开源|如何使用CNN将视频从2D到3D进行自动转换(附源代码)

    http://www.sohu.com/a/128924237_642762 全球人工智能 文章来源:GitHub 作者:Eric Junyuan Xie 它是如何运行的? 在运行代码之前,请先根据官 ...

  9. http://bugs.mysql.com/bug.php?id=72123

    今天某个环境发生了这个bug. http://bugs.mysql.com/bug.php?id=72123

  10. 算法之路 level 01 problem set

    2992.357000 1000 A+B Problem1214.840000 1002 487-32791070.603000 1004 Financial Management880.192000 ...