EF Code First DBContext and Transactions
27,047
- 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();
}
Author by
Admin
Updated on September 17, 2020Comments
-
Admin over 3 years
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?
- Does
-
Lukazoid over 12 yearsBe sure to be using Sql 2008 or later as the database (or have the MSDTC service running on the client). Previous versions will escalate the transaction to a distributed transaction on the second
SaveChanges
. This is due to howDbContext
internally handles the opening and closing of its connection. -
JarrettV over 12 yearsIs is possible to get an identity from the first save changes? I always see Id = 0.
-
Sunny about 12 years@JarrettV - I think your issue is because of the IsolationLevel settings. Lowering it might help...
-
renegadeMind about 12 yearsThis wont work with EF 4.3.1. We will have to open the connection on the Objectcontext explicitly before we call context.SaveChanges().
-
Ladislav Mrnka about 12 years@renegadeMind: Of course this will work with DbContext. What you describe is advanced way used when you want to avoid distributed transaction.
-
renegadeMind about 12 years@LadislavMrnka Yes you are correct; but don't we want to avoid DTC by default? I assumed that we do and hence my answer!