Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF 4.1 Code First - single context or multiple contexts?

Could anyone offer any advice on whether it is best practice to have a single context or multiple contexts?

For example, should I have a single context as follows:

   public class MyContext
      : DbContext
  {
      public DbSet<Company> Companies { get; set; }

      public DbSet<Country> Countries { get; set; } 

      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
          modelBuilder.Configurations.Add(new CountryConfiguration());
          modelBuilder.Configurations.Add(new CompanyConfiguration());
          base.OnModelCreating(modelBuilder);
      }
  }

Or would I be better creating a separate context for Companies and Countries? So ConpanyContext and CountryContext which would both expose a single DbSet property.

It may just be personal choice, but our database is going to consist of 100s of entities. I'd therefore like to get this right to begin with.

Many thanks,

Paul.

like image 572
P2l Avatar asked Apr 07 '11 14:04

P2l


People also ask

Can we use multiple DbContext in Entity Framework?

Multiple DbContext was first introduced in Entity Framework 6.0. Multiple context classes may belong to a single database or two different databases.

Can you have multiple DbContext?

You can have multiple contexts for single database. It can be useful for example if your database contains multiple database schemas and you want to handle each of them as separate self contained area.


1 Answers

A simple rule of thumb: one schema/domain, one context.

like image 143
Diego Mijelshon Avatar answered Oct 12 '22 09:10

Diego Mijelshon