Using asynchronous save changes in an Entity Framework with multiple contexts

I am using EF 6 with a UoW template. I have several contexts defined in my UoW, since I use data from multiple databases. Everything seems to work correctly except for the CommitAsync function that I defined. Here is the code I have:

public async Task CommitAsync() { try { using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { if (_context1 != null) await _context1.SaveChangesAsync(); if (_context2 != null) await _context2.SaveChangesAsync(); scope.Complete(); } } catch (DbEntityValidationException ex) { //.. } } 

When I run this code, saving changes in both contexts, I get:

Transaction Manager has disabled remote / network transaction support. (Exception from HRESULT: 0x8004D024)

Waiting for _context2.SaveChangesAsync (); where the error occurs. If I remove TransactionScope from this function, the code seems to work without errors. I hesitate to delete an area for several contexts.

Just in case this helps, here is the code I use to call this function:

  state.Name = "Texas"; _uow.StateRepository.Update(state); user.FirstName = "John"; _uow.UserRepository.Update(user); await _uow.CommitAsync(); 

Thanks!

+6
source share
1 answer

Using two connections in the same area requires MSDTC.

You can enable MSDTC to solve this problem. But it does not work with many HA solutions and is slow.

The only way to avoid using MSDTC is to use the same connection for everything that needs to be done. Since you are using multiple databases that are more complicated than usual. You need to use SqlConnection.ChangeDatabase or issue the appropriate SQL to switch between databases on the same connection. The connection must be open.

Alternatively, you can use three part names to refer to objects (for example, DB1.dbo.MyTable ).

There is no other way. Either MSDTC, or sharing the same connection.

+2
source

All Articles