Database Migrations

Using Database Migrations

Wrapt projects are completely compatible with Entity Framework Database Migrations.

As usual, if you are only using one Startup and appsettings file, migrations work as they always would. If you are using multiple environments, migrations in Entity Framework currently require you to set the environment manually before you run your migration differentiating between the right appsettings file.

If you'd like to use migrations you will need to set ASPNETCORE_ENVIRONMENT before running dotnet ef to let the host builder locate the appropriate settings file. Here's some examples for Windows, Bash, and PowerShell.

If you'd like to track the feature request for an inline command in EF, you can follow the Github issue.

When running migrations, make sure your UseInMemoryDatabase setting is set to false in your appsettings. This should be the case by default on all environments that are not Development.

Example

  1. Make sure you have dotnet ef installed. To install it globally run:

    dotnet tool install -g dotnet-ef
  2. Set your env variable (e.g. Prod) that matches the environment name in launchsettings:

    Powershell

    $Env:ASPNETCORE_ENVIRONMENT = "Prod"

    Bash

    export ASPNETCORE_ENVIRONMENT=Prod
  3. Perform your first migration. For example:

    dotnet ef migrations add "InitialMigration" --project Infrastructure.Persistence --startup-project WebApi --output-dir Migrations

    Your migrations should be under the project you are running them on, so in this case Infrastructure.Persistence

  4. To add additional migrations, you can do something like this. Again, make sure that your ASPNETCORE_ENVIRONMENT has been set.

    dotnet ef migrations add "added X column to y entity" --project Infrastructure.Persistence --startup-project WebApi --output-dir Migrations
  5. To push the updates to your database, you can run this:

    dotnet ef database update -p Infrastructure.Persistence -s WebApi

Common Db Migration Error

If you're getting an error like the below, make sure that your connection string is set in your appsettings.json file and UseInMemoryDatabase is set to false.

Unable to resolve service for type 'Microsoft.EntityFrameworkCore.Migrations.IMigrator'. This is often because no database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.