MVC BaseController处理CRUD操作
我想重构我的基本CRUD操作,因为它们非常重复,但我不确定最好的方法。 我的所有控制器都inheritanceBaseController,如下所示:
public class BaseController : Controller where T : EntityObject { protected Repository Repository; public BaseController() { Repository = new Repository(new Models.DatabaseContextContainer()); } public virtual ActionResult Index() { return View(Repository.Get()); } }
我像这样创建新的控制器:
public class ForumController : BaseController { }
很好,很容易,因为你可以看到我的BaseController
包含一个Index()
方法,这意味着我的控制器都有一个Index方法,并将从存储库加载他们各自的视图和数据 – 这是完美的。 我在编辑/添加/删除方法上苦苦挣扎,我的存储库中的Add
方法如下所示:
public T Add(T Entity) { Table.AddObject(Entity); SaveChanges(); return Entity; }
再次,好又简单,但在我的BaseController
我显然不能这样做:
public ActionResult Create(Category Category) { Repository.Add(Category); return RedirectToAction("View", "Category", new { id = Category.Id }); }
我通常会如此:任何想法? 我的大脑似乎无法通过这个…; – /
您可以添加所有实体共享的接口:
public interface IEntity { long ID { get; set; } }
并使您的基本控制器要求:
public class BaseController : Controller where T : class, IEntity
这将允许您:
public ActionResult Create(T entity) { Repository.Add(entity); return RedirectToAction("View", typeof(T).Name, new { ID = entity.ID }); }
您还应该考虑使用dependency injection来实例化控制器,以便注入而不是手动实例化您的存储库,但这是一个单独的主题。
不确定问题是什么,你不能使CRUD点也是通用的吗?
public virtual ActionResult Create(T entity) where T : IEntity { Repository.Add(entity); return RedirectToAction("View", this.ModelType, new { id = entity.Id }); }
这假定:
我实际上没有尝试过这个,但是我已经完成了与它相似的脚手架,并且该模式运行良好。 如果无法修改或扩展您的POCO(或您正在使用的任何对象模型),它可能会很粘。
上述就是C#学习教程:MVC BaseController处理CRUD操作分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1021444.html