Cannot attach the file *.mdf as database

.net database entity-framework


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.

6/10/2013 6:14:27 PM

Accepted Answer

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.

7/14/2016 1:41:28 PM

Popular Answer

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).

Related Questions


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