Cannot attach the file *.mdf as database
Basically I've followed a tutorial and decided to delete the .mdf
file afterwards.
Now whenever I try to run the application I get the following error (the title of this thread). The code where I get the error is shown below (ASP.NET MVC 4):
OdeToFoodDB db = new OdeToFoodDB();
public ActionResult Index()
{
var model = db.Restaurants.ToList();
return View(model);
}
My connection string is the following:
<add name="DefaultConnection"
connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=OdeToFoodDb;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\OdeToFoodDb.mdf"
providerName="System.Data.SqlClient" />
I've tried looking at the SQL Server Object Explorer but it looks the following:
Also, in Server Explorer I don't see any data connections.
And when I try to add a new connection in Server Explorer I don't see any databases named OdeToFoodDb
.
Sorry for this wide question but I'm new to Entity Framework and don't quite get what's wrong here.
Solution 1:
I think that for SQL Server Local Db you shouldn't use the Initial Catalog
property.
I suggest to use:
<add name="DefaultConnection"
connectionString="Data Source=(LocalDb)\v11.0;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\OdeToFoodDb.mdf"
providerName="System.Data.SqlClient" />
I think that local db doesn't support multiple database on the same mdf file so specify an initial catalog is not supported (or not well supported and I have some strange errors).
Solution 2:
Take a look at this: Entity Framework don't create database
I would try giving the database a different name. Sometimes you can run into problems with SQL Express when trying to create a database with the same name a second time. There is a way to fix this using SQL Server Management Studio but it's generally easier to just use a different database name.
Edit This answer was accepted because it confirms the bug and the workaround used by OP (renaming database could help). I totally agree that renaming the database is not really an acceptable way, and does not totally solve the issue. Unfortunatly I didn't check the other ways to really solve it in SSMS.
Solution 3:
-
From Package Manager Console run:
sqllocaldb.exe stop v11.0
sqllocaldb.exe delete v11.0
Run your project
- Register a user