6

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.

2 Answers 2

6

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

2
  • I would like to do it this way if performance is ok. I'm a bit concerned what performance will be like creating an instance of the context when it has to deal with 100+ configuration classes in OnModelCreating. This is made more of an issue by using this in a WCF service whereby it will be creating a new instance on each service call.
    – P2l
    Commented Apr 8, 2011 at 9:12
  • @Paul: OnModelCreating is called ONCE, not every time you create an instance. Commented Apr 8, 2011 at 11:07
2

If at all possible, try and split them along meaningful lines.

100 entities in a context might seem bad, but think of your alternative, 100 different contexts?

Then you'd have to do things like

using(CompanyContext cc = new CompanyContext)
{
}

using (CountryContext cc = new CountryContext)
{
}

If you needed to query multiple tables you'd have nested contexts and it would get ugly. You'd start having things like

using(CompanyContext comp = new CompanyContext)
    {
        using (CountryContext country = new CountryContext)
       {
       }
    }

I can't imagine performance would be improved going that way, but I'm sure maintenance would be a pain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.