2

I have read and seen few projects that talks about splitting or multiple DbContext and I'm not sure what is the best practice.. should I create each DbContext for each entity or have all entity in one DbContext?

this is what I have for now.

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; }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Nick Kahn
  • 19,652
  • 91
  • 275
  • 406
  • checkout this answer http://stackoverflow.com/questions/21341636/how-can-i-tell-the-web-api-castle-windsor-routing-engine-to-use-a-different-da/21355365#21355365 – Ehsan Feb 18 '14 at 05:51

1 Answers1

2

Actually you don't need have to create one DbContext for each Entity. But you can have multiple DbContext for a single database. For an example let's say you want to separate your business aspect and security aspect of the application into two different modules. Then of course you can have two different context such as SecurityContext which has all the entities related to Security and BusinessContext consists of Business related entities. Ex:

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; }
}
Rakhita
  • 4,493
  • 1
  • 16
  • 15