Entity Framework Core 2.1: Tools – Update-Database

In this series of entries we are talking about Entity Framework commands. We already saw:

  1. Get-Help
  2. Add-Migration

Now let’s see the Update-Database command. The idea of ​​this command is that, after creating the corresponding migrations, you are probably going to want the changes expressed in the migrations to be reflected in your database. The Update-Database command performs exactly this.

In the case of the dotnet CLI, this command is:

dotnet ef database update

If we use the command Get-Help on Update-Database, we can see the list of parameters of this command, of which we can highlight:

  • Migration: The migration to which we want to update. For example: Suppose we have 3 migrations pending, but we only want to update the database with the first migration, then we can use this parameter to indicate that we only want to select this migration to work, and that for the moment we can ignore the other 2.
  • Context: Define the Data Context to use

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

Examples

Example 1. Basic use: The basic use of this command would be in the case of only having one data context and wanting to apply all the pending migrations. For this we can use, in the Package Manager Console:

Update-database

Or, in the dotnet CLI:

dotnet ef database update

Example 2. Excluding migrations: Suppose the following scenario, we have 3 migrations created which have not been executed in the database, we want to execute the first 2 migrations, and therefore, we do not want to apply the third one. For this we can use the Migration parameter.

It is important to remember that migrations have an order, which is the order of creation. If we have migrations A, B and C, which are in ascending order of creation, if we apply migration B, then migration A is going to be applied, since all migrations prior to migration B must be applied to be able to apply migration B.

So, for our example, suppose we have the following pending migrations:

  1. First
  2. Second
  3. Third

We want to apply the first two, and not the third, for that we must execute the following command in the Package Manager Console:

Update-Database -Migration Second

In the dotnet CLI we would do the following:

dotnet ef database update Second

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s