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.
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.