Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 855
Stephen Paul Avatar asked Jul 15 '16 10:07

Stephen Paul


3 Answers

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.

like image 104
chaosifier Avatar answered Nov 09 '22 15:11

chaosifier


Please look at the SQL Server Object Explorer (Visual Studio -> View -> SQL Server Object Explorer). If it contains the 'DatabaseName' database then please try to delete it.

like image 9
Alexander Zinoviev Avatar answered Nov 09 '22 16:11

Alexander Zinoviev


If you create your database with SQL (meaning DB already exists), put the line DROP DATABASE [databaseName] at the beginning of the file databaseName.sql

This will delete the whole DB and its definition (schema), now you can start with creating your new DB.

like image 1
sosay Avatar answered Nov 09 '22 15:11

sosay