EF Code First DBContext and Transactions

27,047
  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();
}
Share:
27,047
Admin
Author by

Admin

Updated on September 17, 2020

Comments

  • Admin
    Admin over 3 years

    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?
  • Lukazoid
    Lukazoid over 12 years
    Be 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 how DbContext internally handles the opening and closing of its connection.
  • JarrettV
    JarrettV over 12 years
    Is is possible to get an identity from the first save changes? I always see Id = 0.
  • Sunny
    Sunny about 12 years
    @JarrettV - I think your issue is because of the IsolationLevel settings. Lowering it might help...
  • renegadeMind
    renegadeMind about 12 years
    This 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
    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
    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!