Dr. Dorian White
Dr. Dorian White

Reputation: 165

How to correctly use a viewmodel

I am new to ASP.net MVC. I am trying to create a viewmodel to display a join of data. Here is some example code:

   public class Person
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }

    public ICollection<Relative> Relatives { get; set; }

}

public class Relative
{
    [Key]
    public int ID {get; set; }
    public Person Person { get; set; }
    public RelationType RelationType { get; set; }
}

public class RelationType
{
    [Key]
    public int ID { get; set; }
    public string Description { get; set; }
}

public class PersonViewModel
{
    public string Name { get; set; }
    public ICollection<string> RelativeNames { get; set; }
    public ICollection<string> RelativeTypes { get; set; }
}

public class PersonContext : DbContext
{
    public DbSet<PersonViewModel> people { get; set; }
}

When I try to create my controller through Visual Studio, I get the following error:

Unable to retrieve metadata for PersonViewModel. One or more validations errors were detected during generation: EntityType 'PersonViewModel' has no key defined. Define the key for this EntityType.

Upvotes: 3

Views: 3674

Answers (2)

haroonxml
haroonxml

Reputation: 366

View Models are convenient classes for passing data between the controller and the view. The reason you are getting this exception is that because you are passing PersonViewModel class into your dbSet. You cannot do this unless PersonViewModel class has a corresponding table. In that case PersonViewModel should not be a view model but should be a entity,a model class to represent your table.

By Looking at your code I am guessing that you have tables for Person and Relative in your database hence you shoud do the following

public class PersonContext : DbContext
{
    public DbSet<Person> Person { get; set; }
    public DbSet<Relative> Relative { get; set; }

}

and populate PersonViewModel through Person and Relative properties of your DbContext classes. This could be done inside the controller or in a repository class if you have one.

Upvotes: 1

IUnknown
IUnknown

Reputation: 898

The error is self explanatory. You need to add an Id field to the PersonViewModel which will have to be decorated with [Key] as you have rightly done in the classes above.

Upvotes: 3

Related Questions