Reputation: 166
I am developing a component where I am using Entity Framework 4.0.
In a particular scenario I need to make use of a TransactionScope
.
try
{
using (TransactionScope t = new TransactionScope())
{
myEntity.MyObjectsOne.Add(new MyObjectOne());
myEntity.MyObjectsTwo.Add(new MyObjectTwo());
myEntity.SaveChanges();
throw new Exception();
t.Complete();
}
}
catch (Exception e)
{
// What should I do?
}
When the transaction fails and thus it is not completed, myEntity will still reflect the changes made i.e. the adding of MyObjectOne
and MyObjectTwo
.
In such case what is the best practice, in order to avoid inconsistency?
Upvotes: 3
Views: 80
Reputation: 44605
The usual way to do what you need to do is to dispose and reload your entity from fresh in the catch block, so that unless the scope is properly committed, your entity gets reloaded as it was before any change was applied to it.
see this question and all answers for more details: Undo changes in entity framework entities
Upvotes: 5