简体   繁体   中英

Any reason not to use nested using EF entities contexts?

using (var context = new FirstEntities())
{
   using (var context1 = new SecondEntities())
   {
   }
}

This works but for some reason doesn't "feel right"... Does anyone know any valid reason not to use nested using statements with entity framework?

Edit: My question is more along the lines if there is a scenario where this type of nesting could cause an exception or a database error rather than if it is advisable from architectural stand point...

By nesting data contexts you will use two database connections at once. It's preferrable to get the data that you need from one context, close that and open the next, and get the data that you need from that context.

This might mean a little more work as you have to plan your code better, but it also means that the application scales better.

If you are using SQL Server, nested contexts within a transaction (using independent database connections) will escalate to a distributed transaction and required a MSDTC service to be installed and running, which is an unnecessary complication if you are connecting to a single database. It is a major pain. If you can manage your contexts so they share a single connection, you can avoid that very unnecessary and undesirable requirement.

A problem with nested contexts is that Entity Framework is not smart enough to know if the connections are to the same database. If they are to different databases, then you need the distributed transaction coordinator service to maintain the integrity of your data between the databases. If the connections are to the same database, you're screwed by the DTC behavior.

With SQL Server 2008 and later, if you don't have multiple connections open to the same database at the same time, the DTC behavior will be able to detect this and let the work continue as expected. For example, instead of nested contexts, you open and close them sequentially: open one, do some work, close it, open the other, do more work, close it, and continue unmolested by the DTC.

Another solution is to manage one underlying database connection so it is shared by the nested contexts. The theory is, without multiple connections, the DTC doesn't get involved. It's a solution I'm working on, but the architecture of Entity Framework makes it a little difficult to implement.

Information related to a connection manager so you don't open identical connections can be found in this answer about multiple connections .

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