asp.net-mvc - 如何正确使用 View 模型

标签 asp.net-mvc viewmodel

我是 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/

相关文章:

android - 什么时候在 ViewModel 中处理 RxJava2 Disposable?

android - 如何获取 ViewModel?

javascript - 在 MVC 5 中刷新局部 View Div

asp.net-mvc - MEF 与通过 MvcContrib 进行协作编程的可移植区域的优缺点

ajax - 如何将 int 数组从 ajax 发送到 c# mvc?

asp.net-mvc - 使用 FormCollection 时,MVC 3 RTM allowedHtml 不起作用

java - 刚刚创建后更新注释

asp.net-mvc - ASP.NET MVC 中的 DDD、 View 模型和验证

asp.net-mvc-4 - ASP.NET MVC ViewModel 继承问题

c# - [A]System.Web.WebPages.Razor.Configuration.HostSection 无法转换为 [B]System.Web.WebPages.Razor.Configuration.HostSection