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?
By default, SaveChanges will execute in a transaction (see the Remarks part in the docs)
If you want more control over the transaction, you can wrap your savechanges block in a TransactionScope. SaveChanges will then pickup your ambient transaction and use that one.
This can be useful when you want a distributed transaction (for example with multiple contexts or if you use WCF).
As you mentioned that you use different models, you would use both ObjectContexts within one TransactionScope (and use some logic with AcceptAllChanges)
Your code would then look like: