Last Updated: February 25, 2016
·
788
· ashutoshraina

Handle the Database is in use problem for EF

If your database is open in SSMS or in VS then dropping and re-creating the database will throw an exception.
Now, we can overcome this problem by taking the database as a singular user.

context.Database.ExecuteSqlCommand("ALTER DATABASE " +       context.Database.Connection.Database + " SET SINGLE_USER WITH ROLLBACK IMMEDIATE");

context.Database.ExecuteSqlCommand("USE master DROP DATABASE " + context.Database.Connection.Database);

For other options that are available look here

http://www.mssqltips.com/sqlservertip/1407/getting-exclusive-access-to-restore-sql-server-databases/