/// <summary>
/// 给model类自动赋值
/// </summary>
/// <param name="sqlstring">获取查询一个model实例的sql语句</param>
/// <param name="obj">model实例对象</param>
/// <returns></returns>
public object selmodel(string sqlstring,object obj)
{
DataTable dtsell = lcommonbll.GetTable(sqlstring);
int count = dtsell.Rows.Count;
if (count == 0)
{
return null;
}
else
{
DataRow dr = dtsell.Rows[0];
#region 另一种方法
//foreach (DataColumn col in dr.Table.Columns)
//{
// PropertyInfo pt = seller.GetType().GetProperty(col.ColumnName);
// if (String.IsNullOrEmpty(dr[col.ColumnName].ToString()))
// {
// break;
// }
// else
// {
// pt.SetValue(seller, dtsell.Rows[0][0], null);
// }
//}
#endregion
foreach (System.Reflection.PropertyInfo pi in obj.GetType().GetProperties())
{
if (pi.CanWrite)
{
try
{
if (dtsell.Rows[0][pi.Name]!=null)
{
pi.SetValue(obj, dtsell.Rows[0][pi.Name], null);
}
else
{
pi.SetValue(obj, null, null);
}
}
catch
{
pi.SetValue(obj, null, null);
}
}
}
return obj;
}
}
.CS调用
Seller seller = new Seller();//实体类
bind BIND = new bind();//绑定方法类
seller = (Seller)BIND.selmodel("select * from seller where SID=2", seller);//赋值