Search code examples
c#entity-frameworkconnectiondrop-database

Make ADO.NET (and EntityFramework) release a database


I'm creating and dropping databases on the fly for some integration tests. I'm doing all the database management at the ADO.NET level. For the tests I'm using Entity Framework because the entities is one part of what I am testing. The problem is that after I do this:

using (ProjectEntities db = new ProjectEntities(cs)) {
}

I cannot drop the database anymore. It says it is in use. How do I release it so it can be dropped?

I actually had the same problem at the ADO.NET level and what I did was:

new SqlCommand("USE [master]", DatabaseConnection).ExecuteNonQuery();

but I'm not sure how to perform something with the same effect for the Entity Framework connection. I've trying manually disposing the db object (although the using clause should guarantee that) and I've also tried manually closing the db.Connection. Neither helped. If I could run SQL directly no the Entity Framework connection, I believe I'll be able to do it. Or maybe there's another way?


Solution

  • You might need to explicitly close all connections, I believe that the connection are being pooled and it's one of the pooled connections that is still maintaining an active connection to the DB. Try using SqlConnection.ClearAllPools

    I blogged about a similar issue in Entity Framework Object Context - AWAITING COMMAND.