How Many DBContext's Should I have

瘦欲@ 提交于 2020-12-08 05:26:09

问题


Using Entity I currently have dbcontext that has every table in it.

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.

So 1 db context per database or many?


回答1:


I went through this same process recently and found some great resources on the subject. Here are a couple that were very helpful:

  • Shrink EF Models with DDD Bound Contexts.
  • How to decide on a lifetime for your ObjectContext.

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 with DbSets and is limited to the ones that are relevant for the current module.

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 single DbContext to simplify things unless the database is very large. With a large database, I would probably break it apart into multiple DbContexts just to limit the overhead and the clutter, and keep things compartmentalized.




回答2:


currently the EF hasnt been made to be broken down into diff dbContexts. Here a great talk about it

What we have done for this case that we have made a project diff from our MVC website just for the database generation and then have separate dbContexts for every requirement.

This way our dbContexts are never large and are easy to maintain



来源:https://stackoverflow.com/questions/16248074/how-many-dbcontexts-should-i-have

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!