(这里是地址:http://www.cnblogs.com/liuju150/archive/2009/09/11/1564994.html)
那么,有三四十张表的话,
还有操作实体的类,
所以我只要通过前台把表单传过来.
我就可以知道要反射到哪个实体,
然后对实体进行相应的赋值.
再反射一个实体操作的类.
就可以实现对实体的增删改操作了
上面是我的数据库表名
下面是我的实体,和实体操作的类名
- private void InsertAndUpdateObj(HttpContext context)
- {
- string ClassName = context.Request.Form["ClassName"].ToString();
- string ClassData = context.Request.Form["ClassData"].ToString();
- string IntOrUpd = context.Request.Form["isIns"].ToString();
- string[] ClassNameArray = ClassName.Split('_');
- string CNStr = "";
- for (int i = 0; i < ClassNameArray.Length; i++)
- {
- CNStr += ClassNameArray[i].Substring(0,1).ToUpper() + ClassNameArray[i].Substring(1).ToLower();
- }
- ClassName = CNStr;
- //反射实体
- Assembly Ab = Assembly.Load("GradView.Library");
- Type type = Ab.GetType("GradView.Library.Data." + ClassName,true,false);
- object obj = Activator.CreateInstance(type);
- DataContractJsonSerializer dcjs = new DataContractJsonSerializer(type);
- MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(ClassData));
- obj = dcjs.ReadObject(ms);
- //反射业务操作
- string opName = "Biz" + ClassName;
- string opMethod = "Insert";
- switch (IntOrUpd)
- {
- case "0": opMethod = "Update"; break;
- case "1": opMethod = "Insert"; break;
- case "2": opMethod = "Delete"; break;
- default: opMethod = "Insert"; break;
- }
- Type opType = Ab.GetType("GradView.Library.Data." + opName,false);
- object opObj = Activator.CreateInstance(opType);
- MethodInfo[] mi = opType.GetMethods();
- for (int i = 0; i < mi.Length; i++)
- {
- if (mi[i].Name == opMethod)
- {
- object[] par = {
- obj
- };
- try
- {
- mi[i].Invoke(opObj,par);
- break;
- }
- catch
- {
- }
- }
- }
- }
所以我只要写这样的方法来实现,
前台就可以通过jQuery把表单里的值组成json
后台接收这个json
就可以对实体进行相应的操作了