博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
MVC 5 Scaffolder + EntityFramework+UnitOfWork Pattern 代码生成工具集成Visual Studio 2013
阅读量:6721 次
发布时间:2019-06-25

本文共 10652 字,大约阅读时间需要 35 分钟。

MVC 5 Scaffolder + EntityFramework+UnitOfWork Pattern 代码生成工具

经过一个多星期的努力总算完成了单表,多表关联(一对多,多对一)的增删改查的代码生成,基本上可以实现不用添加任何代码完成对数据表的操作。

 

下个阶段打算集成.net 4.5的认证和授权已经用户注册和角色管理

 

一旦有更好的方式我会把它集成到模板中实现自动生成。所以很希望得到大家的帮助。在这里我先抛砖引玉了。

 

 

Demo和所有源代码代码在

 

 

 

先看一下我的Demo实例

 

 

 

 

 

 

 

实体类的结构

Order 与 OrderDetail 一对多,OrderDetail 与 Product 多对一,Order与Product则是多对多的关系。

 

实现的操作界面如下图

查询界面

功能:

1/新增操作 : 页面跳转到新增页面

2/删除操作 : 选择记录或单击行上的删除 弹出确认框 是否删除改记录

3/编辑操作 : 单击行上的编辑图标页面跳转到编辑页面

4/查询操作 : 在Search 文本框中输入关键字会根据后台每个字段的查询,选择需要显示的字段

5/Table功能 :字段显示勾选,分页显示,所有功能都是服务端实现

 

新增页面

功能:

布局:上部表头,下部的Tab为表体明细

一对多 :表体用table显示

多对一 :用Dropdownlist进行选择

表体明细的操作 :使用popup modal的方式操作

单击保存后,系统会自动合并表头表体一起提交到后台进行保存

 

编辑页面

功能:

加载数据:会根据主从关系把表头/表体的数据一次性加载

编辑数据:对表体明细的的操作类似新增页面,但对表体进行删除操作时会进行提示是否真的要删除后台数据。

保存数据:一次性提交所有表头/表体数据到后台进行操作。

 

 

上述这些功能完全可以代码生成 不需要做任何修改

 

 

项目结构

View层的代码

Index :查询Table List

Create :新增页面

Edit : 编辑页面

EditForm :Partial View内嵌在Create 和Edit页面中

_OrderDetailForm : pupup 子表维护表单页面

 

Create,和Edit页面通过Ajax Post 把数据提交到后台的Controller进行操作

代码如下

 

 

通过Jquery 获取表头和表体数据 序列化成Json对象然后Post到后台

 

 

 

 

Controller层代码

这里就只贴Create方法的代码

 

public class OrdersController : Controller    {        //private StoreContext db = new StoreContext();        private readonly IOrderService _orderService;        private readonly IUnitOfWorkAsync _unitOfWork;        public OrdersController(IOrderService orderService, IUnitOfWorkAsync unitOfWork)        {            _orderService = orderService;            _unitOfWork = unitOfWork;        }        // GET: Orders/Index        public ActionResult Index()        {            var orders = _orderService.Queryable().AsQueryable();            return View(orders);        }        // Get :Orders/PageList        // For Index View Boostrap-Table load  data         [HttpGet]        public ActionResult PageList(int offset = 0, int limit = 10, string search = "", string sort = "", string order = "")        {            int totalCount = 0;            int pagenum = offset / limit + 1;            var orders = _orderService.Query(new OrderQuery().WithAnySearch(search)).OrderBy(n => n.OrderBy(sort, order)).SelectPage(pagenum, limit, out totalCount);            var rows = orders.Select(n => new { Id = n.Id, Customer = n.Customer, ShippingAddress = n.ShippingAddress, OrderDate = n.OrderDate }).ToList();            var pagelist = new { total = totalCount, rows = rows };            return Json(pagelist, JsonRequestBehavior.AllowGet);        }        // GET: Orders/Details/5        public ActionResult Details(int? id)        {            if (id == null)            {                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);            }            Order order = _orderService.Find(id);            if (order == null)            {                return HttpNotFound();            }            return View(order);        }        // GET: Orders/Create        public ActionResult Create()        {            return View();        }        // POST: Orders/Create        // To protect from overposting attacks, please enable the specific properties you want to bind to, for more details see http://go.microsoft.com/fwlink/?LinkId=317598.        [HttpPost]        //[ValidateAntiForgeryToken]        public ActionResult Create([Bind(Include = "OrderDetails,Id,Customer,ShippingAddress,OrderDate")] Order order)        {            if (ModelState.IsValid)            {                order.ObjectState = ObjectState.Added;                foreach (var item in order.OrderDetails)                {                    item.OrderId = order.Id;                    item.ObjectState = ObjectState.Added;                }                _orderService.InsertOrUpdateGraph(order);                _unitOfWork.SaveChanges();                if (Request.IsAjaxRequest())                {                    return Json(new { success = true }, JsonRequestBehavior.AllowGet);                }                DisplaySuccessMessage("Has append a Order record");                return RedirectToAction("Index");            }            if (Request.IsAjaxRequest())            {                var modelStateErrors = String.Join("", this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors.Select(n => n.ErrorMessage)));                return Json(new { success = false, err = modelStateErrors }, JsonRequestBehavior.AllowGet);            }            DisplayErrorMessage();            return View(order);        }        // GET: Orders/Edit/5        public ActionResult Edit(int? id)        {            if (id == null)            {                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);            }            Order order = _orderService.Find(id);            if (order == null)            {                return HttpNotFound();            }            return View(order);        }        // POST: Orders/Edit/5        // To protect from overposting attacks, please enable the specific properties you want to bind to, for more details see http://go.microsoft.com/fwlink/?LinkId=317598.        [HttpPost]        //[ValidateAntiForgeryToken]        public ActionResult Edit([Bind(Include = "OrderDetails,Id,Customer,ShippingAddress,OrderDate")] Order order)        {            if (ModelState.IsValid)            {                order.ObjectState = ObjectState.Modified;                foreach (var item in order.OrderDetails)                {                    item.OrderId = order.Id;                    //set ObjectState with conditions                    if (item.Id <= 0)                        item.ObjectState = ObjectState.Added;                    else                        item.ObjectState = ObjectState.Modified;                }                _orderService.InsertOrUpdateGraph(order);                _unitOfWork.SaveChanges();                if (Request.IsAjaxRequest())                {                    return Json(new { success = true }, JsonRequestBehavior.AllowGet);                }                DisplaySuccessMessage("Has update a Order record");                return RedirectToAction("Index");            }            if (Request.IsAjaxRequest())            {                var modelStateErrors = String.Join("", this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors.Select(n => n.ErrorMessage)));                return Json(new { success = false, err = modelStateErrors }, JsonRequestBehavior.AllowGet);            }            DisplayErrorMessage();            return View(order);        }        // GET: Orders/Delete/5        public ActionResult Delete(int? id)        {            if (id == null)            {                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);            }            Order order = _orderService.Find(id);            if (order == null)            {                return HttpNotFound();            }            return View(order);        }        // POST: Orders/Delete/5        [HttpPost, ActionName("Delete")]        //[ValidateAntiForgeryToken]        public ActionResult DeleteConfirmed(int id)        {            Order order = _orderService.Find(id);            _orderService.Delete(order);            _unitOfWork.SaveChanges();            if (Request.IsAjaxRequest())            {                return Json(new { success = true }, JsonRequestBehavior.AllowGet);            }            DisplaySuccessMessage("Has delete a Order record");            return RedirectToAction("Index");        }        // Get Detail Row By Id For Edit        // Get : Orders/EditOrderDetail/:id        [HttpGet]        public ActionResult EditOrderDetail(int? id)        {            if (id == null)            {                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);            }            var orderdetailRepository = _unitOfWork.Repository
(); var orderdetail = orderdetailRepository.Find(id); var orderRepository = _unitOfWork.Repository
(); var productRepository = _unitOfWork.Repository
(); if (orderdetail == null) { ViewBag.OrderId = new SelectList(orderRepository.Queryable(), "Id", "Customer"); ViewBag.ProductId = new SelectList(productRepository.Queryable(), "Id", "Name"); //return HttpNotFound(); return PartialView("_OrderDetailEditForm", new OrderDetail()); } else { ViewBag.OrderId = new SelectList(orderRepository.Queryable(), "Id", "Customer", orderdetail.OrderId); ViewBag.ProductId = new SelectList(productRepository.Queryable(), "Id", "Name", orderdetail.ProductId); } return PartialView("_OrderDetailEditForm", orderdetail); } // Get Create Row By Id For Edit // Get : Orders/CreateOrderDetail [HttpGet] public ActionResult CreateOrderDetail() { var orderRepository = _unitOfWork.Repository
(); ViewBag.OrderId = new SelectList(orderRepository.Queryable(), "Id", "Customer"); var productRepository = _unitOfWork.Repository
(); ViewBag.ProductId = new SelectList(productRepository.Queryable(), "Id", "Name"); return PartialView("_OrderDetailEditForm"); } // Post Delete Detail Row By Id // Get : Orders/DeleteOrderDetail/:id [HttpPost, ActionName("DeleteOrderDetail")] public ActionResult DeleteOrderDetailConfirmed(int id) { var orderdetailRepository = _unitOfWork.Repository
(); orderdetailRepository.Delete(id); _unitOfWork.SaveChanges(); if (Request.IsAjaxRequest()) { return Json(new { success = true }, JsonRequestBehavior.AllowGet); } DisplaySuccessMessage("Has delete a Order record"); return RedirectToAction("Index"); } // Get : Orders/GetOrderDetailsByOrderId/:id [HttpGet] public ActionResult GetOrderDetailsByOrderId(int id) { var orderdetails = _orderService.GetOrderDetailsByOrderId(id); if (Request.IsAjaxRequest()) { return Json(orderdetails.Select(n => new { OrderCustomer = n.Order.Customer, ProductName = n.Product.Name, Id = n.Id, ProductId = n.ProductId, Qty = n.Qty, Price = n.Price, Amount = n.Amount, OrderId = n.OrderId }), JsonRequestBehavior.AllowGet); } return View(orderdetails); } private void DisplaySuccessMessage(string msgText) { TempData["SuccessMessage"] = msgText; } private void DisplayErrorMessage() { TempData["ErrorMessage"] = "Save changes was unsuccessful."; } protected override void Dispose(bool disposing) { if (disposing) { //_unitOfWork.Dispose(); } base.Dispose(disposing); } }

 

 

 

 

Popup Modal编辑子表数据代码

 

  

 所有代码都是根据Entity 类型 和字段名进行生成,理论上针对业务系统都可以模板化,只要模式定下来什么代码都可以生成。

转载地址:http://dccmo.baihongyu.com/

你可能感兴趣的文章
区块链是什么?彻底理解只要150行java代码!
查看>>
使用MaxCompute Java SDK 执行任务卡住了,怎么办?
查看>>
《鹿鼎记》的第一遍读后感作文3600字
查看>>
66.添加自定义监控项目 配置邮件告警与测试及处理问题
查看>>
阿里云应用高可用服务公测发布
查看>>
芯片、半导体和集成电路之间的区别是什么?
查看>>
圣诞要礼物手势大全,礼物在哪里?
查看>>
OSChina 周日乱弹 ——我自己能发呆到世界毁灭
查看>>
OSChina 周二乱弹 —— 好好告别啊!不要舌吻!
查看>>
使用Cygwin和 mingw 安装 python paramiko模块
查看>>
前端那些事之hack篇
查看>>
结合COMSOL,浅谈多场耦合
查看>>
开发人员学Linux(2):VirtualBox中安装CentOS7系统设置
查看>>
HttpURLConnection原生JAVA http請求
查看>>
CentOS/Linux 开放80、8080端口或者开放某个端口
查看>>
Storm配置属性和操作命令
查看>>
react-native-scrollable-tab-view 自定制 tabBar
查看>>
Oracle执行计划 SQL语句执行效率问题查找与解决方法
查看>>
Android ViewFlipper触摸动画
查看>>
开发小组
查看>>