【问题标题】:How to correctly use a viewmodel如何正确使用视图模型
【发布时间】:2012-08-12 23:52:22
【问题描述】:

我是 ASP.net MVC 的新手。我正在尝试创建一个视图模型来显示数据的连接。下面是一些示例代码:

   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 创建控制器时,出现以下错误:

无法检索 PersonViewModel 的元数据。在生成过程中检测到一个或多个验证错误: EntityType 'PersonViewModel' 没有定义键。定义此 EntityType 的键。

【问题讨论】:

    标签: asp.net-mvc viewmodel


    【解决方案1】:

    错误是不言自明的。您需要向 PersonViewModel 添加一个 Id 字段,该字段必须使用 [Key] 进行修饰,正如您在上面的类中所做的那样。

    【讨论】:

    • 啊。我只是感到困惑。我以前从未指定带有主键的视图;我在考虑 SQL Server 视图。
    • 哦,ViewModel 绝对不是领域模型。见Do viewmodels need keys?
    【解决方案2】:

    视图模型是在控制器和视图之间传递数据的便捷类。您收到此异常的原因是因为您将 PersonViewModel 类传递到您的 dbSet。除非 PersonViewModel 类有相应的表,否则您不能这样做。在这种情况下,PersonViewModel 不应该是一个视图模型,而应该是一个实体,一个代表您的表格的模型类。

    通过查看您的代码,我猜您有 Person 和 Relative 表 在您的数据库中,因此您应该执行以下操作

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

    并通过 DbContext 类的 Person 和 Relative 属性填充 PersonViewModel。这可以在控制器内部完成,如果有的话,也可以在存储库类中完成。

    【讨论】:

    • 我试图使用 Code First 来生成表格。我有或没有的布局有可能吗?
    • 是的,你有正确的代码。请看这里的例子msdn.microsoft.com/en-us/data/gg685467.aspx
    • 我遇到了类似的问题。您的链接显示了如何创建模型、控制器、DbContext 以及如何搭建它的示例。我看不出这与根据问题创建 ViewModel 有何关系。我错过了什么吗?
    猜你喜欢
    • 1970-01-01
    • 2011-04-16
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 2016-01-30
    • 1970-01-01
    相关资源
    最近更新 更多