从数据库读取数据Table后转成对应的实体泛型方法
2016-11-05 17:48
405 查看
1每次读取数据库的数据都是一个DataTable表,以前是傻傻的每个表都写一个转换的类,后来自己研究一个泛型方法,适用于所有转换
publicIList<C_AccountModel>GetAccountList(refstringerrMsg)
{
returnC_SQLHelper.ExcuteList<C_AccountModel>("select*fromAccountorderbyIDdesc",CommandType.Text,referrMsg,null);
}
2注意的地方
a:数据库表的字段必须与实体一样否则反射的时候装载不了。
///<summary> ///返回一个集合 ///</summary> ///<typeparamname="T2">要传入的实体</typeparam> ///<paramname="strSql">sql语句或者存储过程类型</param> ///<paramname="sqlComType">sql语句或者存储过程类型</param> ///<paramname="pars">Sql参数数组</param> ///<returns></returns> publicstaticList<T2>ExcuteList<T2>(stringstrSql,CommandTypesqlComType,refstringerrMsg,paramsSqlParameter[]pars) { try { using(SqlConnectionconn=newSqlConnection(s_ConnectionString)) { SqlDataAdaptersda=newSqlDataAdapter(strSql,conn); if(pars!=null) { sda.SelectCommand.Parameters.AddRange(pars); } sda.SelectCommand.CommandType=sqlComType; DataTabledt=newDataTable(); sda.Fill(dt); if(dt.Rows.Count>0) { List<T2>list=newList<T2>(); Typet=typeof(T2); foreach(DataRowdrindt.Rows) { T2model=(T2)Activator.CreateInstance(t); PropertyInfo[]pros=t.GetProperties(); foreach(PropertyInfopinpros) { stringcolName=p.Name; if(dt.Columns.Contains(colName)) { if(p.CanWrite==false)continue; objectcellValue=dr[colName]; if(cellValue!=DBNull.Value) { p.SetValue(model,cellValue,null); } } } list.Add(model); } returnlist; } else { returnnull; } } } catch(Exceptionex) { errMsg=ex.ToString(); returnnull; } } 调用
2注意的地方
a:数据库表的字段必须与实体一样否则反射的时候装载不了。
相关文章推荐
- 删除数据库所有数据 附带sp_MSforeachtable使用方法
- 通过序列化和反序列化泛型数据实体集合来实现持久化数据对象的方法
- [DNN学习所得]CBO——简化从数据库读取数据并实例化对象的有效方法
- VC中连接mdb数据库及其数据读取方法
- PHP-Excel读取导入Excel数据到数据库(2003,2007通用)使用方法
- php从数据库中读取数据生成xml文件的方法
- 用C#编程从数据库中读取图片数据导进Excel文件的方法(如何从数据库中读取保存的文件,直接打开,中间不保存到本地)
- VC中连接mdb数据库及其数据读取方法
- SQL跨数据库读取数据的方法
- 递归方法读取数据库中的数据,添加到TreeView中
- 数据库连接方式读取不到Excel数据值的解决方法
- 比较C#三种方法实现读取Execl数据到数据库
- CodeIgniter读取数据库数据的几种方法。
- 用C#编程从数据库中读取图片数据导进Excel文件的方法
- [转]数据库连接方式读取不到Excel数据值的解决方法
- asp.net中读取数据库数据的方法
- 读取数据库数据到html table中
- 用C#编程从数据库中读取图片数据导进Excel文件的方法(如何从数据库中读取保存的文件,直接打开,中间不保存到本地)
- 通过序列化和反序列化泛型数据实体集合来实现持久化数据对象的方法
- ADO.NET Entity framework 中 实体的对应数据库中text类型的问题 (更新) :asp.net entity 传入的表格格式数据流(TDS)远程过程调用(RPC)协议流不正确。参数 3 ("@0"): 数据类型 0