Entity Framework Core 2.1: Tools – Drop-Database

We continue the theme of the Entity Framework commands! Commands that we have already seen:

Drop-Database

This command is used to delete a database. It does not hurt to say that you should be careful when using a command like this. In the dotnet CLI, this command is as follows:

dotnet ef database drop

If we use the help command on this command, we are shown a list of parameters that it accepts, of which we highlight the following:

  • Context: The data context to be used
  • WhatIf: It informs you which is the database that would be eliminated in case of executing the command. This option can be used in the Package Manager Console.
  • Dry-Run: It informs you which is the database that would be eliminated in case of executing the command. This option can be used in the dotnet CLI.

There are other parameters which you can see using the Get-Help command.

Examples

Basic use: The basic use of this command would be to pass only the data context that refers to the database that we want to eliminate. Assuming that ApplicationDbContext is our data context, then in the Package Manager Console we can use the following command:

drop-Database -context ApplicationDbContext

In the dotnet CLI, we would use the following command:

dotnet ef database drop --context ApplicationDbContext

Verifying the action previously: If you want to make sure that the correct database is going to be erased, you can use the WhatIf option in the Package Manager Console (dry-run in the dotnet CLI), this will allow you to obtain the name of the database that will be deleted, without being actually deleting it:

drop-Database -context ApplicationDbContext -whatif

This results in a message indicating the database to be deleted when using the command with said Data Context. An example of the result of the previous command:

What if: Performing the operation “Drop-Database” on target “database ‘MyDatabase’ on server ‘(localdb)\mssqllocaldb'”

This message says that the database delete operation will be applied to the database named “MyDatabase” located on the server “(localdb) \ mssqllocaldb“.

In the dotnet CLI, the equivalent command is:

dotnet ef database drop --context ApplicationDbContext --dry-run

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 )

Connecting to %s