Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to maintain transaction in Linq To Entites

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?

like image 887
Mox Shah Avatar asked Dec 28 '11 09:12

Mox Shah


People also ask

How does Entity Framework maintain 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. When we execute another operation, the Entity Framework creates a new transaction.

Does SaveChanges commit?

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.

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.

How do I save changes in Entity Framework?

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.


1 Answers

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.

like image 134
scartag Avatar answered Sep 23 '22 21:09

scartag