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, or B) assurances that this'll all work out just fine.
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.
- Is it possible to create a generic Repository class for all my objects?
- ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value
- DateTime property error in LINQ where clause
- Entity Framework Code First Many to Many Setup For Existing Tables
- Find records that contains at least one word of a string
- Mocking dbContext vs Repository
- Undo changes in entity framework entities
- EF Core stored procedure different returning result
- Combine list of parents with list of children
- Unable to create migrations after upgrading to ASP.NET Core 2.0