Given my reservations in another question and my comments here explaining why this is not a final solution, I will try to give a more specific implementation:
public abstract class GenericController<T> : Controller where T : class { protected YourEFContext _dataSource; public GenericController() { _dataSource = new YourEFContext(); } public virtual ActionResult Details(int id) { var model = _dataSource.Set<T>().Find(id); return View(model); } } public class CustomerController : GenericController<Customer> { }
This is all the code that is required for /Customers/Details/42 to load the client with identifier 42 loaded from the Entity Framework context. The "common" part is solved by the Entity Framework method DbContext.Set<T>() , which returns the DbSet<TEntity> for the corresponding entity, in this case the DbSet<Customer> , which you can request.
However, there are many problems using this code:
- You do not want your controller to know about your access to data. As you can see, the controller uses the
YourEFContext property, which is closely related to the Entity Framework. You will want to distract this in the repository template. - You do not want your controller to create an instance of data access, this must be entered.
- You do not want your controller to return database objects. You are looking for ViewModels and Mapper.
- You do not want your controller to access data. Move data access to the service level, which also contains your business logic, draw it again using the repository template.
Now your question is actually: "Does the Enterprise Library data block have a method such as GetDataSet<T> ", so you donโt need to refer to customer and product in your general controller, but unfortunately, t find this because I donโt used EntLib for several years. This will help if you show the code that is currently used to access your database.
The ultimate goal you are looking for:
[ MVC ] <=> [ Service ] <=> [ Repository ] View ViewModel Controller BusinessModel BusinessLogic DataModel Database
Your controller only talks to your service to create / read / update / delete business models and performs the mapping between ViewModels and BusinessModels (in <=> ). The service contains business logic and a business model (DataContacts when using WCF) and, in turn, maps ( <=> ) for and from DataModels and talks with your repository to save your models.
I understand that it can be a little difficult to understand right away, and probably why most ASP.NET MVC tutorials start at all three levels in one application. Check out ProDinner for a better approach.
source share