arch / UnitOfWork

A plugin for Microsoft.EntityFrameworkCore to support repository, unit of work patterns, multiple database with distributed transaction supported, and MySQL multiple databases/tables sharding supported.
MIT License
1.32k stars 343 forks source link

Fix InvalidOperationException on SaveChangesAsync and transaction scope #148

Closed djechelon closed 3 years ago

djechelon commented 3 years ago

I have experienced the following problem on invoking SaveChangesAsync with a single unit of work

System.InvalidOperationException: A TransactionScope must be disposed on the same thread that it was created. 
   at System.Transactions.TransactionScope.Dispose (System.Transactions.Local, Version=5.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51)
   at Arch.EntityFrameworkCore.UnitOfWork.UnitOfWork`1+<SaveChangesAsync>d__12.MoveNext (Microsoft.EntityFrameworkCore.UnitOfWork, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null)
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw (System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Private.CoreLib, Version=5.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)

The cause is that for some reason the compile forces the call to the SaveChangesAsync method with optional units of work.

By looking around (not so around, it looks like that it is necessary to use another constructor of TransactionScope when using an async context.

rigofunc commented 3 years ago

thanks