由于LINQ中的更新数据库操作是通过查询获取某个类后再对类的属性进行一一修改,再更新的方法。这种方法的缺点是,当某个类的属性(也就是数据库某个表的字段特别多的时候)特别多的时候更新比较麻烦,而且如果以后增加或删除表中字段,代码也要随之修改,而有的时候我们就会忘记了,代码如下:
JT_JiBenQingKuang tmpJiaTing = new JT_JiBenQingKuang();
tmpJiaTing = dc.JT_JiBenQingKuangs.Single(t => t.FB_ID.Equals(jiaTing.FB_ID));
tmpJiaTing.FB_Address = jiaTing.FB_Address;
tmpJiaTing.FB_DiBao_RenShu = jiaTing.FB_DiBao_RenShu;
tmpJiaTing.FB_DiBao_ShiFou = jiaTing.FB_DiBao_ShiFou;
tmpJiaTing.FB_DuShengZiNvZheng_ShiFou = jiaTing.FB_DuShengZiNvZheng_ShiFou;
tmpJiaTing.FB_GongYiLin_MuShu = jiaTing.FB_GongYiLin_MuShu;
tmpJiaTing.FB_GongYiLin_ShiFou = jiaTing.FB_GongYiLin_ShiFou;
tmpJiaTing.FB_HeZuoYL_RenShu = jiaTing.FB_HeZuoYL_RenShu;
tmpJiaTing.FB_HeZuoYL_ShiFou = jiaTing.FB_HeZuoYL_ShiFou;
tmpJiaTing.FB_JieZha_ShiFou = jiaTing.FB_JieZha_ShiFou;
tmpJiaTing.FB_TongDian_ShiFou = jiaTing.FB_TongDian_ShiFou;
tmpJiaTing.FB_XingJiWenMingHu_ShiFou = jiaTing.FB_XingJiWenMingHu_ShiFou;
tmpJiaTing.FB_YiMin_ShiFou = jiaTing.FB_YiMin_ShiFou;
tmpJiaTing.WD_ID = jiaTing.WD_ID;
dc.SubmitChanges();
我通过反射机制和动态执行的方式解决对每个属性进行赋值的操作。
1、使用PropertyInfo[] properties = ((JT_JiBenQingKuang)tmpJiBenQQ).GetType().GetProperties();方法获取某个类的所有属性。
2、通过动态执行的方式把获取的所有属性动态地赋值。
public string GenerateCode(string className, IList<string> includePropertys)
{
StringBuilder sb = new StringBuilder();
sb.Append("using System;");
sb.Append(Environment.NewLine);
sb.Append("using System.Reflection;");
sb.Append(Environment.NewLine);
sb.Append("using DangAnGuanLi.SQLServerDAL;");
sb.Append(Environment.NewLine);
sb.Append("namespace DynamicCodeGenerate");
sb.Append(Environment.NewLine);
sb.Append("{");
sb.Append(Environment.NewLine);
sb.Append(" public class HelloWorld");
sb.Append(Environment.NewLine);
sb.Append(" {");
sb.Append(Environment.NewLine);
sb.Append(" public void OutPut(ref " + className + " Dest," + className + " Source)");
sb.Append(Environment.NewLine);
sb.Append(" {");
foreach (string includeProperty in includePropertys)
{
sb.Append(Environment.NewLine);
sb.Append(" Dest." + includeProperty + " = Source." + includeProperty + ";");
}
sb.Append(Environment.NewLine);
sb.Append(" }");
sb.Append(Environment.NewLine);
sb.Append(" }");
sb.Append(Environment.NewLine);
sb.Append("}");
return sb.ToString();
}
使用以上方法后就不必对每个属性进行一一赋值,当有数据库字段增减时也不用管他了,非常方便。
(这种方法是不是太复杂了,如果有更好的方法告诉我一声啊。huqitu@163.com)