好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

c# – 实体框架创建与模型中每个类相对应的单独数据库

我已经开始在ASP.NET MVC4中使用Entity框架了.

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

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

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

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

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变量中.

查看更多关于c# – 实体框架创建与模型中每个类相对应的单独数据库的详细内容...

  阅读:55次