user396491
user396491

Reputation: 941

EF Code First DBContext and Transactions

I would like know what is the best possible way to implement transactions with DBContext. In particular,

  1. Does DbContext.SaveChanges implement transaction internall if i change multiple entities?
  2. If i want to call DbContext.SaveChanges multiple times(same contxet/different contxets), how transaction can be achieved?

Upvotes: 53

Views: 29743

Answers (2)

Lakshitha Kanchana
Lakshitha Kanchana

Reputation: 1235

For asynchronous operation do the following.

using(var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
    // Do something 
    await context.SaveChangesAsync();
    // Do something else
    await context.SaveChangesAsync();

    scope.Complete();
}

References: learn.microsoft.com/en-us/ef/ef6/saving/transactions

Upvotes: 0

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364249

  1. Yes. SaveChanges uses transaction internally.
  2. Use TransactionScope to wrap multiple calls to SaveChanges

Example:

using(var scope = new TransactionScope(TransactionScopeOption.Required,
    new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }))
{
    // Do something 
    context.SaveChanges();
    // Do something else
    context.SaveChanges();

    scope.Complete();
}

Upvotes: 76

Related Questions