【问题标题】:MVC3 Model to a database ViewMVC3 模型到数据库视图
【发布时间】:2012-11-23 17:42:59
【问题描述】:

我想在 MVC3 上创建一个模型,但不是为表创建模型,而是为我的数据库中的视图创建一个模型。我知道对于表的模型,我需要在创建模型时指定主键,否则我会收到一些错误消息。由于视图没有主键/外键,我该如何为视图创建模型?

【问题讨论】:

  • 您使用的是什么 DBMS?你在用 EF 吗?
  • Sql 服务器管理工​​作室。是的,我正在使用 EF
  • DBMS == Sql Server 2005/2008/2012?

标签: database asp.net-mvc-3 view


【解决方案1】:

在任何与 EF 一起使用的 MVC 应用程序中,您可能有不同的模型来在 db 中创建表,或者为不创建任何表的视图创建概念模型。表的创建取决于您将在类中定义的模型类的属性继承自 DbContext。请注意,此类及其关系类中存在的任何属性都将在 db 中创建表。因此,要创建仅在视图中使用的模型,您可以定义与其他表创建者模型没有任何关系的模型,并且在继承的 DbContext 类中没有定义。然后你可以将它们作为模型或类在视图中显示数据。控制器及其相关视图应使用相同的模型,不会发生错误。

public class datacontext : DbContext
{
    public DbSet<Person> people { get; set;}
    public DbSet<Address> address { get; set;}
}
public class Person
{
    [Key]
    public int ID { get; set;}
    public String Name { get; set;}
}
public class Address
{
    [Key]
    public int ID { get; set;}
    public Country country { get; set;}
    public String Details { get; set;}
}
public class Country
{
    [Key]
    public int ID { get; set;}
    public String Name { get; set;}
}
public class Work_Field//without any key definition
{
    public String Title { get; set;}
    public String Description { get; set;}
}

这里我们有这些表:Person、Address、Country(虽然它没有在 datacontext 类中定义) 在此示例中,您可以使用 Work_Field 作为视图模型,或许可以使用一些 DataAnnotations,如 [Required],... 以强制用户不要将参数留空等等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-03
    相关资源
    最近更新 更多