EF Code First DBContext and Transactions
Asked Answered
C

2

53

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?
Colin answered 17/5, 2011 at 9:10 Comment(0)
S
76
  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();
}
Snuff answered 17/5, 2011 at 9:15 Comment(6)
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.Sines
Is is possible to get an identity from the first save changes? I always see Id = 0.Mendes
@Mendes - I think your issue is because of the IsolationLevel settings. Lowering it might help...Baresark
This wont work with EF 4.3.1. We will have to open the connection on the Objectcontext explicitly before we call context.SaveChanges().Disposal
@renegadeMind: Of course this will work with DbContext. What you describe is advanced way used when you want to avoid distributed transaction.Snuff
@LadislavMrnka Yes you are correct; but don't we want to avoid DTC by default? I assumed that we do and hence my answer!Disposal
L
0

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

Lancelle answered 16/5, 2023 at 11:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.