Rollback changes made to Database in Entity Framework .NET

c# entity-framework-6 rollback sql-server unit-testing

Question

I am writing unit test cases for testing a framework. The unit test adds and modifies the data in an existing database. I need to rollback all the changes done to database after a test finishes, i.e. delete the rows added and revert the rows modified.

I am using Entity Framework 6 for accessing the database. The underlying database is SQL Server. Is there any support provided by EF6 to achieve this?

Presently I am storing the changes in a list and I refer the this list for cleaning up the database. But using this approach leaves some residue randomly. I am not sure of the reason though, maybe some race condition or something.

Looking for some minimal and smart alternative for it. Thanks in advance :)

1
3
2/20/2016 8:12:43 PM

Popular Answer

you can wrap your test in a transaction and don't commit changes:

using (TransactionScope scope = new TransactionScope()) {
    //do your stuff
}

But for unit testing propouses you can use Effort - Entity Framework Unit Testing Tool which provide in-memory database operations.

EDITED to reply last comments

You can use an overloaded TransactionScope contructor to control the IsolationLevel, so you can choose to read uncommited changes or not.

If your proxy isn't inside the Transaction, please, check that the connection string is the same, so ado.net can identify the connection and enlist the connection in the same transaction. If the connection string is not the same, you probably will need to activate the Distributed Transaction Coordinator. Here you have an explanation how DTC scalation occurs: TransactionScope automatically escalating to MSDTC on some machines?

3
5/23/2017 12:13:49 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow