We help IT Professionals succeed at work.
Get Started

Can't get transaction rollback working for Entity Frameworks 6

181 Views
Last Modified: 2015-12-08
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..?
Comment
Watch Question
LordWabbit
Commented:
This problem has been solved!
Unlock 1 Answer and 2 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE