ASP.NET MVC and Web API – Fix – Cannot attach the file as database

ASP.NET MVC and Web API
Fix / how-to
Cannot attach the file ‘{0}’ as database ‘{1}’

.

Copy a project, delete the database, and
assume the runtime will re-create the database

Scenario:

You have a project with a database, and the app runs successfully

You copy the project, and delete the database file in the App_Data folder

Next time you run the app, it shows this error:

fix-cannot-attach-database

.

This error appears because your computer still has a setting configured for the database in the original project. You need to delete that setting.

.

How to fix, Visual Studio 2015

Open the Package Manager Console. Run these commands:

sqllocaldb stop MSSQLLocalDB
sqllocaldb delete MSSQLLocalDB

.

Then, you can run your app again, and the setting will be re-created for the new/copied project.

.

How to fix, Visual Studio 2013

Open the Package Manager Console. Run these commands:

sqllocaldb stop v11.0
sqllocaldb delete v11.0

.

Then, you can run your app again, and the setting will be re-created for the new/copied project.

.

Some inspiration for this document was sourced from this SO answer.

 

Copy project, re-use the existing database

Scenario:

You have a project, and copy it.

When you run the app, it complains:

fix-cannot-attach-database-copy

 

How to fix

In Web.config, change the value for the “initial catalog” part of the connection string.

Perhaps you can change the name to better match the name of the copied project.

For example, an original project was called “GetAllGetOne”, so its initial catalog value was “DBGetAllGetOne”.

The copied project was called “EditDelete”, so change the initial catalog value to “DBEditDelete”.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: