ASP.NET MVC4 Code First - 'Cannot attach the file as database' exception

asp.net asp.net-mvc-4 database ef-code-first entity-framework

Question

I'm using Code First concept in Entity Framework and I'm constantly getting the following exception while starting application:

Cannot attach the file 'C:\Users\Admin\Documents\Visual Studio 2012\
Projects\Pro\Pro.Web\App_Data\Pro.mdf' as database 'Pro'.

I've put this in Global.asax.cs but also without success:

Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ProWebContext>());
        var ctx = new ProWebContext();
        ctx.Database.Initialize(true);

I've checked under App_Data directory and there no database created. Also, under Server Explorer there is nothing under Data Connections. Everything was working fine yesterday and today not working at all. I've tried to connect to LocalDB with SQL Server Management studio but it says it cannot connect to local database. Any ideas what could be a problem?

Thanks!

1
4
3/29/2013 11:01:01 AM

Accepted Answer

I found the solution. With newest SQL Server Management studio there is no problem in connecting to the local database. Connection needs to be established like this:

enter image description here

After logging in we can still see old database present even if there is nothing under App_Data directory and under Data Connections in Server Explorer in Visual Studio. When we delete that database from SQL Server Management studio and start application again there will be no more errors while attaching database.

5
3/31/2013 5:00:38 PM

Popular Answer

I just got into the same problem, and yet the answers above helped, the solution was different.

In my case, I was reusing a project that has already created it´s database. And since the name in the config was the same, it was throwing the exception, missleading the real solution.

It worth checking the database is not created and is different than the ones you used before. Change the name and go ahead.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow