11

When EntityFramework query was wrapped in DbContextTransaction created with dbContext.Database.BeginTransaction() method I've got the following error:

at NMemory.Transactions.Transaction.EnsureTransaction(Transaction& transaction, IDatabase database) at NMemory.Tables.Table2.Update(IQueryable1 query, IUpdater1 updater, Transaction transaction) at NMemory.Tables.Table2.NMemory.Tables.IBulkTable.Update(TableQuery1 query, Expression1 updater, Transaction transaction) at NMemory.Linq.QueryableEx.Update[T](IQueryable1 queryable, Expression1 updater, Transaction transaction) at Effort.Internal.Common.DatabaseReflectionHelper.WrapperMethods.UpdateEntities[TEntity](IQueryable1 query, Expression1 updater, Transaction transaction)

I found a post on Effort GitHub repository with similar error (https://github.com/tamasflamich/effort/issues/29) where it was fixed using DbTransaction instead, created by dbContext.Database.Connection.BeginTransaction() method. I tried using DbTransaction instead and it works, but now I'm wondering what's the difference between those two?

msmolcic
  • 6,407
  • 8
  • 32
  • 56

1 Answers1

0

If we take the documentation for DbTransaction and DbContextTransaction we have:

DbTransaction:

  • Defines the core behavior of database transactions so it's independant from EntityFramework and comes from System.Data.Common
  • you have some additionnals methods like CommitAsync, DisposeAsync, SaveAsync, ... and implements the interface IdbTransaction

DbContextTransaction:

  • Comes from System.Data.Entity
  • Implement IDisposable only

I found another explanation here: https://github.com/dotnet/efcore/issues/24074

Beginning a transaction on Database is an EF Core API which will internally call the corresponding lower-level ADO.NET DbConnection API. It's recommended to use DbContextTransaction, that way EF Core is properly aware that a transaction has been started - that can be important depending on exactly how you use the DbContext.

Dmidecode
  • 66
  • 1
  • 2
  • 6
  • Please link to English sites. Also, an important difference is that DbcontextTransaction is part of the old EF6. – Gert Arnold Oct 28 '22 at 13:38