何时在实体框架中使用多个DbContext? [英] When to use more than one DbContext in the Entity Framework?
问题描述
DbContext具有反映数据库中不同实体集的属性.
DbContext have properties reflecting the different sets of entities in the database.
我正在使用使用MEF的插件体系结构,并且已经阅读了类似的SO问题,回答了我的问题的一部分(
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?)
但是在我的核心应用程序中,我有多个DbContext(衍生物)将少数几个实体组合在一起.例如 SecurityDbContext
ConfigurationDbContext
.
But in my core app, I have multiple DbContext (derivatives) that group handfuls of entities together. e.g. SecurityDbContext
ConfigurationDbContext
.
这些上下文中仅包含几个 DbSet
属性.
These contexts only have a few DbSet
properties in them.
我所引用的文章提供了一种方法,通过该方法,您可以拥有一个中央DbContext并在插件库中配置模型.这意味着整个应用程序和插件只有一个DbContext.
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.
我知道EF6每个DB支持多个DbContext-这是否意味着我可以根据需要创建任意数量的DbContext-包括在插件中?
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?
我假设DbContext只能(在查询中)联接到其中定义的实体,而与DbContext是否用于同一数据库无关.
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.
任何建议表示赞赏
推荐答案
我认为在阅读其他用户提供的所有链接后,我会分享自己的结论.
I thought I'd share my conclusion after reading all the links other users have provided.
很明显,我创建的 DbContext
类没有包含足够的实体,因为我发现自己使用编写的帮助程序功能将实体对象与其他上下文分离,以便可以附加它们在其他情况下.
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.
我遇到的下一个问题是如何在插件中处理DbContext.该插件很可能需要使用核心"实体,但也需要定义自己的实体.
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.
使用MEF和此问题的解决方案,决定在整个系统中使用单个DbContext(
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.
尽管我已经读到大型DbContext的性能很差,但目前一切都很好-继续前进,具体取决于实体的数量和单个DbContext的性能,我很可能会分解成一系列较小的DbContext并拥有一个包含所有内容的DbContext来管理数据库同步.
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
这篇关于何时在实体框架中使用多个DbContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!