Home > Enterprise >  Difference between DbContextTransaction.Commit() and context.Database.CommitTransaction()
Difference between DbContextTransaction.Commit() and context.Database.CommitTransaction()

Time:01-04

What is the main differences between two commit types?

            bool adresVarmi = false;
            using (var trans = dbContext.Database.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted))
            {
                adresVarmi = dbContext.MUSTERI_ADRES.Where(x => x.MUSTERI_TANIM_ID == dto.MusteriId).AsNoTracking().Count() > 0;
                trans.Commit();
                dbContext.Database.CommitTransaction();
            }

Is it same for high traffic applications?

CodePudding user response:

context.Database.CommitTransaction()

is equivalent to

context.Database.CurrentTransaction.Commit()

The main purpose for that method is to be able to commit the current transaction from code which did not call BeginTransaction() or has no access to the returned IDbContextTransaction object. It will fail if there is no current active transaction.

Since you are the one who starts the transaction and have access to the returned IDbContextTransaction object, it is preferable to issue Commit() on it rather than using CommitTransaction() method.

i.e. the following is preferred (note that you shouldn't call both as in your example since the second will fail because there won't be active transaction after the Commit() call):

using (var trans = dbContext.Database.BeginTransaction(System.Data.IsolationLevel.ReadUncommitted))
{
    // do something...
    trans.Commit();
}
  •  Tags:  
  • Related