One transaction with multiple dbcontexts

后端 未结 4 2024
心在旅途
心在旅途 2020-12-05 02:55

I am using transactions in my unit tests to roll back changes. The unit test uses a dbcontext, and the service i\'m testing uses his own. Both of them are wrapped in one tra

4条回答
  •  感动是毒
    2020-12-05 03:36

    In the first scenario, you are nesting DbContexts. A connection to the database is opened for each on of them. When you call your service method within the using block, a new connection is opened within the TransactionScope while there is another one already open. This causes your transaction to be promoted to a distributed transaction, and partially committed data (the result of the DbContext.SaveChanges call in the service) not being available from your outer connection. Also note that distributed transactions are far slower and thus, this has the side effect of degrading performance.

    In the second scenario, while you open and close three connections, only one connection is open at the same time within your transaction. Since these connections share the same connection string, the transaction won't be automatically promoted to a distributed connection and thus, each subsequent connection within the transaction has access to the changes performed by the previous connection.

    You may try adding the Enlist=false parameter to your connection string. This would disable automatic enlisting in a distributed transaction, causing an exception to be raised in your first scenario. The second scenario would keep working flawlessly if you are using SQL Server 2008 and beyond, since the transaction won't get promoted. (Prior versions of SQL Server will still promote the transaction in this scenario.)

    You may also find helpful this great answer to a quite similar question.

提交回复
热议问题