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> { }
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;
}
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.. ;-/