我应该有几个DBContext [英] How Many DBContext's Should I have
问题描述
使用实体,我目前拥有dbcontext,其中包含每个表.
Using Entity I currently have dbcontext that has every table in it.
我想知道这是否每个人都在做,还是例如每个模块都有一个上下文.对我而言,dbcontext是将模型映射到数据库的连接,并且由于只有一个数据库,因此我只需要一个数据库.
I'm wondering if that's what everyone does, or do you have a context per module for example. To me the dbcontext was a connection to map the models to a database, and since there is only one database, I only need one.
在我走得太远之前,我想看看是否合适.
Before I get too far along I want to see if that's appropriate.
那么每个数据库有1个db上下文还是很多?
So 1 db context per database or many?
推荐答案
我最近也经历了同样的过程,并在该主题上找到了很多有用的资源.这对夫妇非常有帮助:
I went through this same process recently and found some great resources on the subject. Here are a couple that were very helpful:
- 具有DDD绑定上下文的收缩EF模型.
- 我正在构建一个桌面应用程序,最终我使用了多个上下文,因此我可以将生命周期与模块而不是应用程序联系在一起.这对我来说非常好,我喜欢我的
DbContext
不会被DbSets
所淹没,并且仅限于与当前模块相关的内容.I was building a Desktop app, and I ended up using multiple contexts so that I could keep the lifetime tied to the module rather than the application. This has worked out very well for me, and I like that my
DbContext
isn't swamped withDbSets
and is limited to the ones that are relevant for the current module.在ASP.NET MVC应用程序中,它有所不同,因为
DbContext
仅在请求中存在,并且在这种情况下,我通常使用单个DbContext
简化操作,除非数据库很大.对于大型数据库,我可能会将其拆分为多个DbContexts
,只是为了限制开销和混乱,并使事情分隔开来.In an ASP.NET MVC app, it is different since the
DbContext
will only live as long as the request, and in those cases, I usually use a singleDbContext
to simplify things unless the database is very large. With a large database, I would probably break it apart into multipleDbContexts
just to limit the overhead and the clutter, and keep things compartmentalized.这篇关于我应该有几个DBContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!