您的位置:首页 > 数据库

从数据库读取数据Table后转成对应的实体泛型方法

2016-11-05 17:48 405 查看
1每次读取数据库的数据都是一个DataTable表,以前是傻傻的每个表都写一个转换的类,后来自己研究一个泛型方法,适用于所有转换

///<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;
}
}

调用


publicIList<C_AccountModel>GetAccountList(refstringerrMsg) { returnC_SQLHelper.ExcuteList<C_AccountModel>("select*fromAccountorderbyIDdesc",CommandType.Text,referrMsg,null); }


  2注意的地方

a:数据库表的字段必须与实体一样否则反射的时候装载不了。


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐