0

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 :)

AndersLindas
  • 137
  • 1
  • 9

1 Answers1

2

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).

cynic
  • 5,305
  • 1
  • 24
  • 40
  • OK. That explains alot. Can I somehow tell EF that I need to perform a synchronization with the database for either all or for some particullar table? I mean, it would be perfect if I could just refresh the _database.Units table. – AndersLindas Jun 25 '12 at 07:40
  • Not really. In your code sample, in the case of rollback you could detach the newly added entites and requery the database for all the Units with the [OverwriteChanges](http://msdn.microsoft.com/en-us/library/system.data.objects.mergeoption.aspx) option. – cynic Jun 25 '12 at 07:46
  • Thanks. I think I'll be able to work around this now. Also, I'm using Code First and DbContext instead of ObjectContext. But found a [link](http://thedatafarm.com/blog/data-access/accessing-objectcontext-features-from-ef-4-1-dbcontext/) that was helpfull access the ObjectContext. – AndersLindas Jun 25 '12 at 08:01