简体   繁体   中英

Is it good practice to have multiple data contexts?

When breaking a solution out into multiple projects, does it make sense to have multiple data contexts or share the context?

Example, for a web portal you have:

App.Service1
App.Service2
App.Web (references Service1 and Service2)

Now would you have it so that Service1 and Service2 share the same DataContext or they each have their own?

Keep in mind that both Service1 and Service2 are both connecting to the exact same database, they are just seperated in order to keep things more isolated.

I'm using EF6.

It's better to share the same context. Multiple contexts make sense when you are aggregating data from different databases.

I would use a single context mainly as it will stop Entity Framework for getting confused with Migrations or Schema change detection if two contexts live on the same database

If separation is a concern and your design allows for it, I would make the context implement two interfaces which is the logical split of Service1 and Service2 and use the interfaces throughout your code.

It is also worth noting you can can't have cross context relationships in regards to navigation properties but that doesn't sound like an issue in your case

In general I would recomment you to use one Context for simplicity, but íf your Data Model (Context) is very large than you will maybe have a better performance if you use more than one Context. But it makes only sense if your entities don't have a relation. And it can be difficult to handle many contexts.

I personally see no use of having two data contexts with the same database. I see your idea to isolate things but I think EF is powerful enough not to do that this way. I use two contexts for different databases as @Darin said.

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