Link to home
Start Free TrialLog in
Avatar of FrancineTaylor
FrancineTaylor

asked on

Can't get transaction rollback working for Entity Frameworks 6

Here's my test code:

    Protected Sub TestEntityTransactions()
        Dim db As New ProdEntities()

        ' Testing the save changes not attached to a transaction
        Dim p As Person = db.People.FirstOrDefault(Function(px) px.PersonID = 8551)

        p.PersonCustom1 = "First;"
        db.SaveChanges()

        Dim transaction As System.Data.Entity.DbContextTransaction

        ' do a commit to the transaction
        transaction = db.Database.BeginTransaction()
        p = db.People.FirstOrDefault(Function(px) px.PersonID = 8551)
        p.PersonCustom1 = p.PersonCustom1 & "second;"
        db.SaveChanges()
        transaction.Commit()
        transaction.Dispose()

        ' do a rollback to the transaction
        transaction = db.Database.BeginTransaction()
        p = db.People.FirstOrDefault(Function(px) px.PersonID = 8551)
        p.PersonCustom1 = p.PersonCustom1 & "rollback;"
        'db.SaveChanges()
        transaction.Rollback()
        transaction.Dispose()

        ' do a commit after a rollback
        transaction = db.Database.BeginTransaction()
        p = db.People.FirstOrDefault(Function(px) px.PersonID = 8551)
        p.PersonCustom1 = p.PersonCustom1 & "fourth;"
        db.SaveChanges()
        transaction.Commit()
        transaction.Dispose()

    End Sub

The resulting string in PersonCustom1 looks like this: "First;second;rollback;fourth;"

I would have expected that it be missing the "rollback;".  I tried without the .Dispose() statements.  I tried with and without the SaveChanges before the rollback.

This is my first experience with Entity Framework.  All the rollback code for framework 6 that I've found on the web seems to indicate that it should be working.  I'm hoping I just missed something simple..?
ASKER CERTIFIED SOLUTION
Avatar of LordWabbit
LordWabbit

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of FrancineTaylor
FrancineTaylor

ASKER

It worked perfectly!  Thanks for such a precise and easy to follow answer...