Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with LocalDB and EF, without using migrations

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

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

Occasionally, even when I don't think I've touched the model, it decides to recreate. That's fine. But it usually results in the error

Cannot drop database because it is currently in use.

So I decided to delete the database entirely. I go into VS, go to the "SQL Server Object Explorer", find the DB and delete it. Now I'm stuck at

Cannot attach the file '{0}' as database '{1}'

I had this happen last night and I just fiddled around until it work (shut down tasks, restart VS, changed the DB and file names in the web.config, etc.

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

But the more important question, how do I prevent myself from getting in this state at all?

like image 526
Dan Friedman Avatar asked Aug 25 '12 02:08

Dan Friedman


People also ask

Do we need EDMX XML file for EF Code First approach?

Code first approach lets us transform our coded classes into database application, which means code first lets us to define our domain model using POCO (plain old CLR object) class rather than using an XML-based EDMX files which has no dependency with Entity Framework.


2 Answers

The SQL Server Object Explorer window can hold a connection to the database. Closing the window and all windows opened from it releases the connection.

like image 200
Edward Brey Avatar answered Sep 29 '22 10:09

Edward Brey


I had the same problem and managed to fix it. The main problem is that EF won't automatically create the database. The solution is not very hard.

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

Then most likely you will get an error message that says that the database does not contain any model metadata. To circumvent this, change your database initialisation to:

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

Now run the application and the database should be there with tables correctly created. Once this step has been successfully executed, you change change your database initializer back to:

Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SomeContext>());
like image 44
Erik Schierboom Avatar answered Sep 29 '22 11:09

Erik Schierboom