MVC BaseController处理CRUD操作 [英] MVC BaseController handling CRUD operations

查看:1773
本文介绍了MVC BaseController处理CRUD操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想,因为他们是很重复重构我的基本的CRUD操作,但我不知道去了解它的最佳方式。我所有的控制器继承BaseController它看起来像这样:

I want to refactor my basic CRUD operations as they are very repetitive but I'm not sure the best way to go about it. All of my controllers inherit BaseController which looks like so:

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());
    }
}

我创造新的控制器,就像这样:

I create new controllers like so:

public class ForumController : BaseController<Forum> { }

尼斯和容易,因为你可以看到我的 BaseController 包含一个指数()方法,这样就意味着我的控制器都有一个指数法和将加载它们各自的观点和数据存储库 - 这个完美的作品。我挣扎于编辑/添加/删除方法,我的添加在我的仓库的方法是这样的:

Nice and easy and as you can see my BaseController contains an Index() method so that means my controllers all have an Index method and will load their respective views and data from the repository - this works perfectly. I'm struggling on Edit/Add/Delete methods, my Add method in my repository looks like this:

public T Add(T Entity)
{
    Table.AddObject(Entity);
    SaveChanges();

    return Entity;
}

再次漂亮和容易的,但在我的 BaseController 我显然不能做的:

Again, nice and easy but in my BaseController I obviously can't do:

public ActionResult Create(Category Category)
{
    Repository.Add(Category);
    return RedirectToAction("View", "Category", new { id = Category.Id });
}

我通常会这样:任何想法?我的大脑似乎无法获得通过该..; - /

as I usually would so: any ideas? My brain can't seem to get pass this.. ;-/

推荐答案

您可以通过添加所有实体共享的接口:

You could add an interface shared by all entities:

public interface IEntity
{
    long ID { get; set; }
}

和使你的基础的控制器需要这样的:

And make your base controller require this:

public class BaseController<T> : Controller where T : class, IEntity

这将允许您:

public ActionResult Create(T entity)
{
    Repository.Add(entity);
    return RedirectToAction("View", typeof(T).Name, new { ID = entity.ID });
}

您也应该考虑使用依赖注入实例化你的控制器,让你的仓库被注入而不是手动实例化,但是这是一个独立的主题。

You should also consider using dependency injection to instantiate your controllers, so that your repositories are injected rather than instantiated manually, but that is a separate topic.

这篇关于MVC BaseController处理CRUD操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆