我是 ASP.net MVC 新手。我正在尝试创建一个 View 模型来显示数据连接。这是一些示例代码:
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; }
}
当我尝试通过 Visual Studio 创建 Controller 时,出现以下错误:
无法检索 PersonViewModel 的元数据。在生成过程中检测到一个或多个验证错误: EntityType“PersonViewModel”没有定义键。定义此 EntityType 的键。
最佳答案
该错误是不言自明的。您需要向 PersonViewModel 添加一个 Id 字段,该字段必须用 [Key] 进行装饰,就像您在上面的类中正确完成的那样。
关于asp.net-mvc - 如何正确使用 View 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11926762/