Suppose I am inserting records in following Tables at the same time
Table 1
Table 2
Table 3
Table 4
Table 5
Now What I want to do is, In-case of any exception or error occurs during insertion in Table 3 , then record which are inserted before that (eg. in Table 1 and Table 2) must be roll back...
How can I manage transaction like this?
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. When we execute another operation, the Entity Framework creates a new transaction.
In Entity Framework, the SaveChanges() method internally creates a transaction and wraps all INSERT, UPDATE and DELETE operations under it. Multiple SaveChanges() calls, create separate transactions, perform CRUD operations and then commit each transaction.
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.
In Entity Framework, the DbContext. SaveChanges method saves all changes made in the context of the database. You can add, modify, and remove data using your context and entity classes.
This is the default behaviour of Entity Framework 4
The transaction is implicit .. as soon as you call savechanges any errors will trigger a rollback.
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