微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

反射实现所有实体的增删改操作(jQuery+json)

续前面的无刷新分页控件,编辑,修改控件的实现,

(这里是地址: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

就可以对实体进行相应的操作了

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐