How to work with LocalDB and EF, without using migrations

I am in VS 2012 RTM, with EF 5. I am doing Code First, but trying to ignore Code Migrations, since I am only in development. To avoid them, I have this set

Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SomeContext>()); 

Sometimes, even when I do not think that I have touched the model, he decides to recreate. It's great. But usually this leads to an error

The database cannot be deleted because it is currently in use.

So I decided to completely delete the database. I go to VS, go to "SQL Server Object Browser", find the DB and delete it. Now i'm stuck in

Unable to attach file '{0}' as database '{1}'

It happened to me last night, and I just staggered until it worked (completing tasks, rebooting VS, changing the database name and files in the web.config file, etc.

So, question 1) How do I get out of this state?

But the more important question is: how can I not get into this state at all?

+7
source share
2 answers

The SQL Object Browser window may contain a database connection. Closing a window and all open windows from it release the connection.

+6
source

I had the same problem and managed to fix it. The main problem is that EF will not automatically create the database. The solution is not very difficult.

First go to Solution Explorer and manually create the database. To do this, go to the folder in which your database is located (usually App_Data ). Right-click this folder and select Add β†’ New Item . Click the Data tab and select SQL Server Database . Make sure you enter the Entity Framework name (which is indicated in the Cannot attach the file '{0}' as database '{1}' error message).

Then, most likely, you will receive an error message stating that the database does not contain model metadata. To work around this, change the database initialization to:

 Database.SetInitializer(new DropCreateDatabaseAlways<SomeContext>()); 

Now run the application, and the database should be there with the tables correctly created. Once this step is successfully completed, you change the change to the database initializer to:

 Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SomeContext>()); 
+5
source

All Articles