MVC BaseController处理CRUD操作

时间:2011-03-18 21:35:20

标签: c# asp.net-mvc asp.net-mvc-3

我想重构我的基本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 });
}
像往常一样:任何想法?我的大脑似乎无法通过这个...; - /

2 个答案:

答案 0 :(得分:2)

您可以添加所有实体共享的界面:

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

让你的基础控制器需要这个:

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

您还应该考虑使用依赖注入来实例化您的控制器,以便注入而不是手动实例化您的存储库,但这是一个单独的主题。

答案 1 :(得分:0)

不确定问题是什么,你不能使CRUD点也是通用的吗?

public virtual ActionResult Create(T entity) where T : IEntity
{
    Repository.Add(entity);
    return RedirectToAction("View", this.ModelType, new { id = entity.Id });
}

这假定:

  • 你的控制器在构建时在基本控制器上设置了一个名为“ModelType”的值,它告诉它应该控制什么样的模型。
  • 您有一个公共接口(IEntity)或已知基类,它具有一组基本属性(如Id),控制器可以使用它们来管理流参数等。< / LI>

我实际上没有尝试过这个但是我已经完成了与它类似的脚手架,并且该模式运行良好。如果无法修改或扩展您的POCO(或任何您正在使用的对象模型),它可能会很粘。

相关问题