EF Code First DBContext and Transactions
I would like know what is the best possible way to implement transactions with DBContext
. In particular,
- Does
DbContext.SaveChanges
implement transaction internall if i change multiple entities? - If i want to call
DbContext.SaveChanges
multiple times(same contxet/different contxets), how transaction can be achieved?
Solution 1:
- Yes.
SaveChanges
uses transaction internally. - Use
TransactionScope
to wrap multiple calls toSaveChanges
Example:
using(var scope = new TransactionScope(TransactionScopeOption.Required,
new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }))
{
// Do something
context.SaveChanges();
// Do something else
context.SaveChanges();
scope.Complete();
}