EF5: Cannot attach the file ‘{0}' as database

2019-01-03 11:49发布

I'm encountering the exact issue as described here (read section "Cannot Attach to Deleted MDF File"), but the solution to the problem is not told there...

In short the issue is that after deleting the .mdf file, the following exception is thrown when I try to access the DB using EF 5.0.

DataException->EntityException->SqlException:
Cannot attach the file ‘{0}' as database '{1}'

I did delete the DB file and now I get that nasty error message when running the application expecting it to use it's initializer. Any way to fix this?

12条回答
疯言疯语
2楼-- · 2019-01-03 12:06

For those still searching for a solution...

Go to View / SQL Server Object Explorer and delete the database from the (localdb)\v11.0 subnode!
enter image description here

There is essentially a local database retained of where the files should be, and if you want to delete the database files make sure you remove them from this explorer utility, not manually.

查看更多
甜甜的少女心
3楼-- · 2019-01-03 12:06

Connect to (LocalDb)\v11.0 using Sql server management studio, delete the db and then do an update-database in package manager console.

查看更多
聊天终结者
4楼-- · 2019-01-03 12:09

Alright.

My solution was simple, I changed to use local server:

I changed the DataSource attribute in the connection string from:

Data Source=(LocalDb)\v11.0;blah

To:

Data Source=.\SQLEXPRESS;blah

Another solution is login to LocalDb via SQL Management Studio, and try to delete that database:

enter image description here

However it didn't work for me, when I try to delete it it says "TITLE: Microsoft SQL Server Management Studio

The Database '{0}' does not exist on the server. (SqlManagerUI)

When I try to detach it the database doesn't appear in the list for detach selection, "Take offline" also takes me to the error above.

Which leads me to think this is a solid bug in LocalDB.

查看更多
Juvenile、少年°
5楼-- · 2019-01-03 12:09

The best and easy answer I just solved it now, Just use ur sql server name as data source, initial catalog be your database name and there you go remove the mdf line

查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-01-03 12:09

In my case I use migrations and in config i simply changed name of dataContext and dataContext class itself (just rename), then try again and that helped

查看更多
Root(大扎)
7楼-- · 2019-01-03 12:13

The easiest fix is to simply change the name of your DB in the connection string. See Rowan Millers blog How to Drop a Database from Visual Studio 2012 for alternate solutions. We hope to fix this problem in a future edition.

查看更多
登录 后发表回答