In addition to what has already been mentioned (problem separation, isolation, etc.), a separate ViewModel stops the leak of abstraction that may appear along with the database model. This is true, especially if you use EF with navigation properties enabled.
Say you have cars and wheels. You show cars in sight.
Case 1 (there is no separate ViewModel for cars): In razor mode, it’s very easy to have something like the following:
public class CarModelFromDB { public string CarName{get;set;} //More properties public IEnumerable<Wheel> Wheel{get;set;} } @model IEnumerable<CarModelFromDB> @foreach(var car in Model) {
Now your logic of getting wheels with cars has leaked into the view, and also allowed you to choose the situation N + 1 . I do not think that there are other ways of testing.
Case 2 (with ViewModel for cars):. In this case, you can limit the presentation by sending only those things that he needs. It might look like this:
public class CarViewModel { public string CarName{get;set;} //More properties public IEnumerable<string> WheelColors{get;set;} } @model IEnumerable<CarViewModel> @foreach(var car in Model) {
Now your viewing code is very limited in terms of what it can do and it will not send any rogue requests to the database. Your controller really controls what kind it gets. You can click the wheel logic there or ideally in some service method that is called from the action method. In addition, you can conduct proper action method testing and feel confident about your system. Hope this helps.
Update
Case 3 (dynamic ViewModel): If you are comfortable with dynamic types , you can avoid all castings and mapping. As long as your gaze gets the properties he needs, he will be happy. No matter where they came from. Thus, the code will be:
public class CarViewModel { public string CarName{get;set;}
A potential drawback / additional work is to make sure that you have tests for the presence of these properties on the model.
Again, as mentioned earlier, this should not be construed as a single size corresponding to all types of solutions. These are some options and are used only if they make sense.