我读过并看到过一些谈论拆分或多个 DbContext 的项目,但我不确定最佳实践是什么。我应该为每个实体创建每个 DbContext 还是将所有实体放在一个 DbContext 中?
这就是我现在所拥有的。
public class PersonsContext : DbContext
{
public PersonsContext() : base("name=EmployeeContext")
{
}
public DbSet<Person> People { get; set; }
}
public class OrderContext : DbContext
{
public OrderContext() : base("name=EmployeeContext")
{
}
public DbSet<Order> People { get; set; }
}
最佳答案
实际上,您不需要为每个实体创建一个 DbContext。但是单个数据库可以有多个 DbContext。举个例子,假设您希望将应用程序的业务方面和安全方面分成两个不同的模块。当然,您可以有两个不同的上下文,例如 SecurityContext,其中包含与安全相关的所有实体,而 BusinessContext 由业务相关实体组成。 例如:
public class SecurityContext : DbContext{
public PersonsContext() : base("name=securitycontext"){
}
public DbSet<User> User { get; set; }
public DbSet<Role> Role { get; set; }
public DbSet<Group> Group { get; set; }
}
public class BusinessContext : DbContext{
public OrderContext() : base("name=businesscontext"){
}
public DbSet<Order> Order { get; set; }
public DbSet<OrderLine> OrderLine { get; set; }
public DbSet<Customer> Customer { get; set; }
}
关于entity-framework - 拆分多个 DbContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21843751/