Reputation: 460
The Controller should not directly use the DB context, and the respository should not know about view models (representation).
The underlying issue is of course to avoid selecting all columns from the DB, only those that are needed.
How is this problem normally solved?
Example 1: DB context in controller:
public ActionResult Products()
{
var model = from p in _context.Products
select new ProductItemViewModel
{
ProductName = p.ProductName
};
return View(model);
}
Example 2: ViewModel in repository:
public ProductItemViewModel Products()
{
return from p in _context.Products
select new ProductItemViewModel
{
ProductName = p.ProductName
};
}
Upvotes: 0
Views: 1058
Reputation: 7359
You really should not have DbContext in your Controller. MVC is a presentation pattern. Generally, accessing the data store (which DBContext is) is not a concern of the presentation layer.
Have a read about MVC Orchestrator classes, as explained by Dino Esposito.
Orchestrator classes are a bit like the service layer for your MVC application. An Orchestrator knows (but not necessarily understands) your presentation model (the 'M') in your MVC, as well as the models your repository accepts or returns. The main aim of Dino's Orchestrator classes is really to remove the application logic from your Controller classes, and also make them easily testable and reusable. Your Controllers are only responsible for the web related processes (e.g. ensuring request is authenticated, or getting information from the HTTP context, or redirecting the request or composing the HTTP response).
You can also have Factory classes that instantiate and map between your presentation and repository models. For example, a ProductFactory knows how to create ProductViewModel object given a ProductFromRepo object (assuming all info that is needed to create a ProductViewModel object is available from a ProductFromRepo object), and/or vice versa. The sole purpose of these Factory classes is to decouple your model mappings from your Orchestrator, and your Repository.
UPDATE: To answer your comment, the design of your repositories depend on you. Often people think it should return the DB models. But your repos could return DTOs or even Domain models. It really depends on how you design your repos and your application architecture.
Upvotes: 1
Reputation: 17485
As per my knowledge and thinking you have to read bit more regarding MVC. This is what I think.
The (M) in MVC is Model that represent data but it represent data from DB or other external resource side that can be represent at View Side. Now problem is View that need to display data sometime need to display data from multiple Model so ViewModel come into the picture.
So in common terms ViewModel represent data that need to be displayed by view. Here ViewModel does not have any other responsibility so it is Passive Model.
ViewModel only be available at Web Side. It should not be exposed or share with BLL or other layer.
Upvotes: 0