Home > Enterprise >  Should ViewModels contain Models? (ASP.NET, Entity Framework)
Should ViewModels contain Models? (ASP.NET, Entity Framework)

Time:04-24

Should view models contain models directly as shown below?

public class ViewModel
{
    public Car Car { get; set; }          // Car model
    public Driver Driver { get; set; }    // Driver model
    public Photo Photo { get; set; }      // Photo model

    public List<Skill> Skills { get; set; }   // List of Skill model
}

or should view models contain another view models:

{
    public CarViewModel CarViewModel { get; set; }
    public DriverViewModel DriverViewModel { get; set; }
    public PhotoViewModel PhotoViewModel { get; set; }

    public List<SkillViewModel> Skills { get; set; }
}

What is the best practice?

CodePudding user response:

It depends on what you are doing, but normally, the second option is the best practice, assuming all of the objects inside the Viewmodel are somehow actually displayed in the View.

Also take into aspect that your ViewModel items represent the thing on the UI, and the Model represents the business logic.

So, your UI-Artefacts (ViewModel objects) are not necessarily associatable to one domain object (Business Logic Object).

So, in your example, "Photo" or "Skills" don't seem to be a logical object in that matter.

They exists on the ViewModel to be displayed, as UI Artefacts, but in the logical domain they would more likely be a property of a logical object, maybe the driver, or something.

  • Related