Search code examples
entity-frameworktransactionstransactionscoperollback

Entity Framework - Model doesnt update after failed transaction


Working on a project using Entity Framework (4.3.1.0). I'm trying to figure out how to make my code work as a transaction, but for me it seems like my model doesnt update after the transaction has failed.

Let me show you:

using (TransactionScope trans = new TransactionScope())
{
    _database.Units.Add(new Unit{ ... });
    var a = false;
    if (a)
    {
        trans.Complete();
        Refresh();
    }
}

Refresh();

What I experience is that after the transactionscope is finished it doesnt roll back to it's previous state. When I run the refresh method I iterate over all the items in Units and insert the values into a ObservableCollection which I display on the screen in a WPF window.

This mechanism works for when I successfully perform the transaction, but when I run the code above, the grid updates with the newly added Unit, but it does not go away after I run Refresh after the transaction.

I have the feeling I'm doing something fundamentaly wrong here :)


Solution

  • Entity Framework does not support transactions for the in-memory tracked entities - its "ObjectStateManager" which you see in the ObjectContext is not a transactional resource. The TransactionScope only "applies" to the database operations (queries, updates) done within it, not the in-memory operations, such as manipulating the object graph (which is what you do).