Database '[DatabaseName]' already exists. Choose a different database name

Stephen Paul picture Stephen Paul · Jul 15, 2016 · Viewed 11.4k times · Source

I'm following this guide illustrating a code-first approach with Entity Framework core. Migrations were functioning correctly until, at some point, I deleted my .mdf file. Since then, executing Update-Database (to apply my migration) throws the following error: Database 'DatabaseName' already exists. Choose a different database name.

Where exactly is this database? How can I remove it permanently?

According to this answer, I need to detach my database from Sql Server, but I'm not sure how to do that now. In Sql Server Management studio, If I execute sp_detach_db DatabaseName it throws error The database 'DatabaseName' does not exist. Supply a valid database name.

Thanks in advance.

UPDATE I see I can also reproduce this database already exists error if I have the database attached in SQL Server Management Studio, and execute the Update-Database command. After I close the management studio, the migration applies without this error. Very confusing to me.

Answer

chaosifier picture chaosifier · Dec 23, 2018

Seems like an instance of LocalDB is still running in the background. Execute the following commands in the console to stop and delete the instance.

sqllocaldb stop
sqllocaldb delete

The Update-Database command should now have no problems.