实习中遇到关于ASP.Net三层中的问题。
之前学习三层都是仿照PetShop的三层还有动软代码生成器中的三层实现。用起来也比较顺手。但是现在公司里用到的三层在DAL里面获取数据列表,在BLL里面进行增、删、改。并且DAL里的每个类都继承自Dal.cs类中其中的实现很多用到了反射机制。比如下面:
这个方法是根据ID获取实体。这里就一串的代码。虽说不用我自己实现,但是总觉得用法上异常了。求解答,发表大家的意见。
public void getModel(Object obj, long ID)
{
Type type = obj.GetType();
string tmpTableName = "";
foreach (PropertyInfo info in type.GetProperties())
{
if (info.Name == "sTableName")
{
tmpTableName = info.GetValue(obj, null) + "";
break;
}
}
if (tmpTableName == "") tmpTableName = sTableName;
StringBuilder strSql = new StringBuilder();
strSql.Append("select top 1 * from " + tmpTableName);
strSql.Append(" where ID=@ID");
SqlParameter[] parameters = { new SqlParameter("@ID", SqlDbType.BigInt, 8)
};
parameters[0].Value = ID;
DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
if (ds.Tables[0].Rows.Count <= 0)
{
obj = null;
return;
}
foreach (PropertyInfo info in type.GetProperties())
{
try
{
string sObjProperty = info.PropertyType + "";
if (sObjProperty.IndexOf("System.Int32") >= 0)
{
if (ds.Tables[0].Rows[0][info.Name].ToString() != "")
info.SetValue(obj, int.Parse(ds.Tables[0].Rows[0][info.Name].ToString()), null);
else
info.SetValue(obj, 0, null);
}
else if (sObjProperty.IndexOf("System.Int64") >= 0)
{
if (ds.Tables[0].Rows[0][info.Name].ToString() != "")
info.SetValue(obj, long.Parse(ds.Tables[0].Rows[0][info.Name].ToString()), null);
else
info.SetValue(obj, 0, null);
}
else if (sObjProperty == "System.Boolean")
{
if (ds.Tables[0].Rows[0][info.Name].ToString() != "")
info.SetValue(obj, bool.Parse(ds.Tables[0].Rows[0][info.Name].ToString()), null);
else info.SetValue(obj, false, null);
}
else if (sObjProperty.IndexOf("System.Decimal") >= 0)
{
if (ds.Tables[0].Rows[0][info.Name].ToString() != "")
info.SetValue(obj, decimal.Parse(ds.Tables[0].Rows[0][info.Name].ToString()), null);
else info.SetValue(obj, 0, null);
}
else { info.SetValue(obj, ds.Tables[0].Rows[0][info.Name].ToString(), null); }
}
catch
{
continue;
}
}
}