4

我已经开始在 ASP.NET MVC4 中使用实体框架。

我在我的Model文件夹中创建了 3 个类,并为每个模型创建了控制器。

现在,当我运行应用程序时,它已经创建了与每个​​模型类对应的单独数据库。

有什么方法可以只使用一个数据库吗?

4

1 回答 1

1

您是否为每个类创建单独的上下文?

public class Employee 
{
    [Key] public int EmpId { get; set; } // < Can I make a suggestion here
                                         // and suggest you use Id rather than
                                         // EmpId?  It looks better referring to 
                                         // employee.Id rather than employee.EmpId
    [Required] public string Fullname { get; set; }
    ...
}

public class AnotherClass
{
    ...
}

然后在上下文中列出所有模型:

public MyDbContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
    public DbSet<AnotherClass> AnotherClasses { get; set; }
}

您可能还想通过在 Context 中使用构造函数来指定连接字符串名称:

public MyDbContext() : base("ConnectionString") {  }

重要的是你的所有模型都在同一个上下文中。

使用上下文

var context = new MyDbContext();
var employees = context.employees.ToList(); // I prefer storing the data as an IList

这告诉 EF 查询数据库并将数据存储在 employees 变量中。

于 2013-04-26T13:09:40.797 回答