I would like know what is the best possible way to implement transactions with DBContext
. In particular,
DbContext.SaveChanges
implement transaction internall if i change multiple entities?DbContext.SaveChanges
multiple times(same contxet/different contxets), how transaction can be achieved?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.
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.
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.
SaveChanges
uses transaction internally.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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With