您的位置:首页 > 数据库

Ado.net利用反射执行SQL得到实体

2013-11-20 12:01 134 查看
public Model.orderParent GetTraceIDforID(string orderid)
{
string sql = string.Format(" select * from orderParent where Id='{0}'", orderid);
DataTable dt = new BaseBLL().DataAccess.QueryDataTable(sql);
if (dt != null && dt.Rows.Count > 0)
{
Model.orderParent data = (Model.orderParent)ReflectionHelper.AssignDataSetToModel(dt, (new Model.orderParent()).GetType());
return data;
}
else
{
return null;
}
}


  

public static Object AssignDataSetToModel(System.Data.DataTable dt, Type objectType)
{
try
{
if (dt.Rows.Count <= 0)
{
return null;
}
System.Reflection.PropertyInfo[] pis = objectType.GetProperties();
Object obj = null;
if (null != pis)
{
Type[] paramTypes = new Type[0];
object[] paramArray = new object[0];
obj = objectType.GetConstructor(paramTypes).Invoke(paramArray);
foreach (PropertyInfo pi in pis)
{
if (pi.DeclaringType.Equals(objectType))
{
int colIndex = getColindex(pi.Name, dt);
if (pi.PropertyType.Name == "Char" || pi.PropertyType.Name == "Int32" || pi.PropertyType.Name == "Single" || pi.PropertyType.Name == "Decimal" || pi.PropertyType.Name == "DateTime" || pi.PropertyType.Name == "Boolean")
{

if (pi.PropertyType.Name == "Int32")
pi.SetValue(obj, dt.Rows[0][colIndex] == DBNull.Value ? 0 : Convert.ToInt32(dt.Rows[0][colIndex]), null);
else if (pi.PropertyType.Name == "Single")
pi.SetValue(obj, dt.Rows[0][colIndex] == DBNull.Value ? 0 : Convert.ToSingle(dt.Rows[0][colIndex]), null);
else if (pi.PropertyType.Name == "Decimal")
pi.SetValue(obj, dt.Rows[0][colIndex] == DBNull.Value ? 0 : Convert.ToDecimal(dt.Rows[0][colIndex]), null);
else if (pi.PropertyType.Name == "DateTime")
pi.SetValue(obj, dt.Rows[0][colIndex] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(dt.Rows[0][colIndex]), null);
else if (pi.PropertyType.Name == "Boolean")
pi.SetValue(obj, dt.Rows[0][colIndex] == DBNull.Value ? false : Convert.ToBoolean(dt.Rows[0][colIndex]), null);
else if (pi.PropertyType.Name == "Char")
pi.SetValue(obj, dt.Rows[0][colIndex] == DBNull.Value ? '0' : Convert.ToChar(dt.Rows[0][colIndex]), null);
}
else
pi.SetValue(obj, dt.Rows[0][colIndex] == DBNull.Value ? "" : dt.Rows[0][colIndex], null);

}
}
}
return obj;
}
catch (Exception ex)
{
throw ex;
}
}


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