MVC BaseController handles CRUD operations

I want to reorganize my basic CRUD operations as they are very repetitive, but I'm not sure if this is the best way. All my controllers inherit a BaseController that looks like this:

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 such new controllers:

 public class ForumController : BaseController<Forum> { } 

It's nice and easy, and as you can see, my BaseController contains an Index() method, so my controllers have an Index method and will load their respective views and data from the repository - this works fine. I am struggling for editing / adding / deleting 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:

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

as I usually like it: any ideas? My brain, it seems, can not get past this ...; - /

+3
source share
2 answers

You can add an interface common to all objects:

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

And make your base controller:

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

This will allow you to:

 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 added rather than created manually, but this is a separate topic.

+2
source

Not sure what the problem is, you also can't make CRUD glasses the same?

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

This suggests that:

  • Your controllers set a value called "ModelType" on the base controller when they are constructed, which means that the "look" of the models that it should control.
  • You have a common interface ( IEntity ) or a well-known base class that has a set of basic properties (for example, Id ) that the controller can use to control flow parameters, etc.

I actually have not tried this, but I made similar forests, and the template works quite well. It can be sticky if you cannot modify or extend your POCO object model (or whatever you use).

0
source

Source: https://habr.com/ru/post/1390323/


All Articles