如何正确使用viewmodel

时间:2012-08-12 23:52:22

标签: asp.net-mvc viewmodel

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

   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的密钥。

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

View Models是在控制器和视图之间传递数据的便捷类。您获得此异常的原因是因为您将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。这可以在控制器内部或存储库类中完成(如果有的话)。