【发布时间】:2013-05-19 06:26:52
【问题描述】:
我想重构我的基本 CRUD 操作,因为它们非常重复,但我不确定最好的方法。我所有的控制器都继承了 BaseController,如下所示:
public class BaseController<T> : Controller where T : EntityObject
{
protected Repository<T> Repository;
public BaseController()
{
Repository = new Repository<T>(new Models.DatabaseContextContainer());
}
public virtual ActionResult Index()
{
return View(Repository.Get());
}
}
我像这样创建新的控制器:
public class ForumController : BaseController<Forum> { }
很好,很简单,你可以看到我的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 });
}
我通常会这样做:有什么想法吗?我的大脑似乎无法通过这个.. ;-/
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-3