sagesky36
sagesky36

Reputation: 4692

One View for multiple models?

If you need to create one View from various entity (models), is it best to create a separate class as a ViewModel containing the specific properties that you need or is it better to create another entity with the specific properties and associate that entity with the rest of the entities in the ORM designer?

Upvotes: 2

Views: 506

Answers (1)

Amin Saqi
Amin Saqi

Reputation: 18977

You can merge any number of models into one model by declaring them a property of the main m odel. Suppose that you have the following models:

public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public int SchoolID { get; set; }

    public virtual School StudentSchool { get; set; }
}

public class School
{
    public School()
    {
        this.Students = new HashSet<Student>();            
    }

    public int SchoolID { get; set; }
    public string ASchoolName { get; set; }

    public virtual ICollection<Student> Students { get; set; }        
}

If you just set the Student class as your view model, you can retrive the School of your student and in this case you doesn't need to do anything.

However we suppose that you also need all schools and all students in your view as your view model. To do this, create another class and add the above classes as its properties:

public class MyModel
{
    List<Student> MyStudents { get; set; }
    List<School> MySchools { get; set; }
}

You can create any complex model you need by this approach...

Upvotes: 1

Related Questions