Entity Framework Core 2.1: Tools – Add Migration

In the last entry we talked about the command line that allows us to perform common tasks with Entity Framework Core. We continue this entry with the command that is used to add migrations.


Let’s now see one of the commands that we have used most so far, the command to add migration: Add-Migration. We use this command after making changes to the Fluent API or one of our models in order to express these changes in C # code, so that we can have a record of these changes before submitting them to the database.

In the dotnet CLI, this command is:

dotnet ef migrations add

If we use Get-Help on Add-Migration, or the -h option in the dotnet CLI, we can see the different parameters which we can use with this command, of which we can highlight:

Name: This is used to give a name to the migration

OutputDir: Defines the place where the migrations will be placed. By default, these are placed in the Migrations directory.

Context: Defines the Data Context to be used. This is essential in situations where you have more than one Data Context in your project.

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


Example 1. Basic use: The basic use of this command would be to simply add a migration in a project of a Data Context. If the name of the migration will be “new”, then in the package manager console we can write:

Add-Migration New

In the dotnet CLI this would be:

dotnet ef migrations add new

Example 2. Multiple Data Contexts: Suppose we have two Data Context, and we want to add a migration with respect to one of them. Let SecondDbContext be the name of the Data Context in question, and let it be “new-index” the name of the migration that we want to add. If we do:

Add-migration new-index

We are going to have an error that says “More than one DbContext was found. Specify which one to use. Use the ‘-Context’ parameter for PowerShell commands and the ‘–context’ parameter for dotnet commands.”

We solve this by using the -Context parameter in the Package Manager Console:

Add-Migration new-index -Context SecondDbContext

In the CLI dotnet with -c:

dotnet ef migrations add new-index -c SecondDbContext

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 )


Connecting to %s