简体   繁体   中英

When to use more than one DbContext in the Entity Framework?

DbContext have properties reflecting the different sets of entities in the database.

I'm using a plugin architecture using MEF and have read similar SO question answering part of my question ( MEF Plugins and EF CodeFirst - How? )

But in my core app, I have multiple DbContext (derivatives) that group handfuls of entities together. eg SecurityDbContext ConfigurationDbContext .

These contexts only have a few DbSet properties in them.

The article i referenced provides a method by which you have one central DbContext and configure the models in the plugin libraries. This would mean there is one DbContext for the whole application and plugins.

I know EF6 support multiple DbContexts per DB - so does that mean I can just create as many DbContexts as needed - including in the plugins?

I'm assuming that a DbContext can only join (in queries) to entities defined in it irrespective of whether the DbContext is for the same DB.

Any advice appreciated

I thought I'd share my conclusion after reading all the links other users have provided.

It was clear that the DbContext classes I had created didn't include enough entities as I found myself using helper functions I'd written to detach entity objects from other contexts so that they could be attached to other contexts.

The next problem I ran up against was how to deal with DbContexts within a plugin. The plugin may well need to use a "core" entity but also define its own.

Deciding to use a single DbContext for the whole system, using MEF and the solution to this question ( MEF Plugins and EF CodeFirst - How? ) I was easily able to manipulate the single DbContext to handle additional entities defined in the plugin.

All is working well at present, although I'd read about poor performance of large DbContexts - moving forward, depending on the number of entities and performance of the single DbContext I may well refactor to break up into a series of smaller DbContexts and have a single DbContext with everything in it for managing the database sync.

hope this helps someone with same question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM