Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Code First DBContext and Transactions

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?
like image 676
user396491 Avatar asked May 17 '11 09:05

user396491


People also ask

Does Entity Framework support transactions?

Entity Framework internally maintains transactions when the SaveChanges() method is called. It means the Entity Framework maintains a transaction for the multiple entity insert, update and delete in a single SaveChanges() method.

Which database function begins a new entity transaction?

Beginning a transaction requires that the underlying store connection is open. So calling Database. BeginTransaction() will open the connection if it is not already opened.

When would you use SaveChanges false AcceptAllChanges ()?

Sometimes though the SaveChanges(false) + AcceptAllChanges() pairing is useful. The most useful place for this is in situations where you want to do a distributed transaction across two different Contexts. If context1. SaveChanges() succeeds but context2.


1 Answers

  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(); } 
like image 126
Ladislav Mrnka Avatar answered Oct 05 '22 22:10

Ladislav Mrnka