Monday, December 1, 2014

LocalDb error: Cannot attach the file ‘sample.mdf’ as database ‘sample.mdf’

In a demo app I  used the LocalDB functionality to host my database files. This should have saved me some time. However when I ran the application, I ended up with the following error message:

{"Cannot attach the file 'C:\\Projects\\SampleApp\\App_Data\\sample.mdf' as database 'sample'."}

Looking at my connection string data inside my web.config, everything looked fine:

<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=Sample;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Sample.mdf" providerName="System.Data.SqlClient" />

But when I opened up the App_Data folder, I found an empty folder. Aha! It seems like you have to create the database file yourself. I opened up the solution, right clicked on the App_Data folder and choose Add –> New item…



Anonymous said...

Thanks this saved me much frustration.

Jules Wensley said...

I have wasted the whole morning trying to sort this.

Then I found your blog.

Such a simple solution.

Brilliant, thank you.

Anonymous said...

Thank you for posting this.

I can't stand M$...

neznamija said...

You are my hero!!!!!

Thank you so much!