Entity Framework: One Database, Multiple DbContexts. Is this a bad idea?

Josh Schultz picture Josh Schultz · Jun 25, 2012 · Viewed 118.4k times · Source

My impression to date has been that a DbContext is meant to represent your database, and thus, if your application uses one database, you'd want only one DbContext.

However, some colleagues want to break functional areas out into separate DbContext classes.

I believe this comes from a good place -- a desire to keep the code cleaner -- but it seems volatile. My gut's telling me it's a bad idea, but unfortunately, my gut feeling is not a sufficient condition for a design decision.

So I'm looking for:

A) concrete examples of why this might be a bad idea;

B) assurances that this will all work out just fine.

Answer

Ladislav Mrnka picture Ladislav Mrnka · Jun 26, 2012

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.

The problem is when you want to use code first to create your database - only single context in your application can do that. The trick for this is usually one additional context containing all your entities which is used only for database creation. Your real application contexts containing only subsets of your entities must have database initializer set to null.

There are other issues you will see when using multiple context types - for example shared entity types and their passing from one context to another, etc. Generally it is possible, it can make your design much cleaner and separate different functional areas but it has its costs in additional complexity.