【问题标题】:Splitting Multiple DbContexts拆分多个 DbContext
【发布时间】:2014-02-18 03:28:09
【问题描述】:

我已阅读并看到很少有项目谈论拆分或多个 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; }
}

【问题讨论】:

标签: entity-framework repository-pattern dbcontext unit-of-work


【解决方案1】:

实际上,您不必为每个实体创建一个 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; }
}

【讨论】:

    猜你喜欢
    • 2018-05-27
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 2021-01-23
    相关资源
    最近更新 更多