Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot drop database because it is currently in use MVC

Tags:

I'm brand new to using MVC, and I'm trying to use an initializer to initialize data into my DB when the application is first started. Here is what I've got in Global.asax.cs:

 System.Data.Entity.Database.SetInitializer(new MyAppInitializer());  MyAppContext db = new MyAppContext();  db.Database.Initialize(true); 

In Web.config, here is my connection string:

<connectionStrings>   <add name="MyAppContext"   connectionString="data source= MyServer; Integrated Security=True; database=MyDatabase"   providerName="System.Data.SqlClient"/> 

This is using MS SQL 2008 R2. My Initializer looks like this:

public class MyAppInitializer : DropCreateDatabaseAlways<MyAppContext> {     protected override void Seed(MyAppContext context)     {         var organizations = new List<Organizations>         {             new Organizations { OrgName = "AT", OrgPhone = 5093333433, OrgOfficeLocation = "ITB", OrgPointOfContact = "Tony", OrgIsActive = 1 },             new Organizations { OrgName = "Libraries", OrgPhone = 5093331122, OrgOfficeLocation = "Holland-Terrell", OrgPointOfContact = "Herald", OrgIsActive = 1 }         };         organizations.ForEach(s => context.Organizations.Add(s));         context.SaveChanges(); 

I made sure I closed my connection to the server and database in SQL Server Management Studio, but multiple people have access to this DB, although none should be using it right now. How can I get it so I can initialize this data in my DB? Thanks!

Edit: I've already got the DB created on the server, but it is completely empty (no tables, procedures, etc). Would this cause an issue?

like image 800
SantasNotReal Avatar asked Jun 13 '13 19:06

SantasNotReal


2 Answers

I faced a similar issue today when using MVC codefirst. After 20 mins of trying out various stuff I noticed that, the "Server Explorer" tab in Visual Studio had a connection open to my database. After I "closed" the connection in the server explorer tab of visual studio, the code was able to run and automatically recreate the database.

like image 104
TwoPea Avatar answered Sep 29 '22 00:09

TwoPea


In SSMS run something like this...

USE master -- be sure that you're not on MYDB ALTER DATABASE MYDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE DROP DATABASE MYDB; 
like image 44
Sam Avatar answered Sep 28 '22 22:09

Sam