I have a problem that I am unable to resolve. My development team have a suite of C# unit tests that run against a unit test database. Before each test, the database needs to be restored to its base-lined start-point. The fastest way to achieve this is to:
- Detach the database.
- Overwrite the .mdf and .ldf files with base-lined backup copies.
- Attach the database.
I perform these actions by invoking Transact SQL commands from C#.
The problem I have is that approximately 50% of the time, opening a connection to the unit test database will fail – the exceptions are of different types – but they all seem to suggest that the database does not exist. If I put in a ‘sleep’ command after the Attach statement then the database can be opened successfully every time. My interpretation of this is that there must be some sort of SQL Server background process that runs against the database to finalise bringing the database on-line. So, directly after executing sp_attach_db, the database is not actually ready for use until after a few milliseconds.
Of course, my solution could be to execute a ‘sleep’ statement after every database attach but there are 800 of these tests so it is vital that the detach/restore/attach process is as fast as possible.
Does anyone have experience of this problem? Does anyone know why the database is not immediately available to accept a connection? Does anyone know how I can detect when the database is ready to accept a connection.
Thanks in advance.
Try to switch off the Pooling on your connections. When Pooling is ON, your connection in the pool is broken when you forcibly close it while detaching the DB, and thus when the connection comes from connections pool – the very first batch will fail.
Simply add to your connection strings
Pooling=noPS: If your tests not so much complex, it can be much faster to run the test inside a transaction and simply roll it back when it finishes to clear the DB