Reputation: 941
I would like know what is the best possible way to implement transactions with DBContext
. In particular,
DbContext.SaveChanges
implement transaction internall if i change multiple entities?DbContext.SaveChanges
multiple times(same contxet/different contxets), how transaction can be achieved?Upvotes: 53
Views: 29743
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
Reputation: 364249
SaveChanges
uses transaction internally.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