Cleaning up EF 6 tests with Transaction Rollbacks

You’ve set up Entity Framework, and you’ve even written integration tests against your code. Your tests create all kinds of sample data in your test database (you aren’t running integration tests against your production database, are you?), and now you need to make sure that the sample data gets cleaned up so the database looks like it did before your test. You could try to do some code to cleanup your data after your test runs, but if your test fails, it can be hard to know exactly how to clean up your data because you can’t guarantee that the data is in a particular state.

There is a better way. I was chatting with @jeremy6d this morning, and he suggested that I use transactions that can be rolled back at the end of a test. The following is how to do so when using Entity Framework 6.

Read More