Jinfu Lin, .NET Developer

avatar

EF Core Migrations in Separate Project

When using EF core code first with migration, you may want to have migration files stored in a separate project, e.g. the migration project is only used in design time/deployment time by the EF migration CLI tool. 

To make this happen:

  1. Create the migration project as a console project because EF migration CLI requires an executable startup project to borrow the runtime. Check here for better understanding.
  2. Add reference to the project where your DbContext is defined.
  3. Add 2 pages: the Microsoft.EntityFrameworkCore.Design package and the Microsoft.EntityFrameworkCore.Tools tool. 

4. The CLI tool needs to be able to discover and create a working instance of a DbContext type in order to gather details about the application's entity types and how they map to a database schema. Normally the tool will get the instance from application services provider where the DbContext is configured. We can also tell the tool to get the instance from a design-time factory by create a factory class implementing the IDesignTimeDbContextFactory<TContext> interface. For more details, check out this document.

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.Infrastructure;
 
namespace Panthera.Data.DbMigration
{
    public class TempPantheraDbContextFactory: IDesignTimeDbContextFactory<PantheraMigrationDbContext>
    {
        public PantheraMigrationDbContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<PantheraMigrationDbContext>();
            optionsBuilder.UseSqlServer("Server=xxx.xxx.xxx.xx;Database=Panthera;User ID=xxxx;Password=xxxx;MultipleActiveResultSets=true");
 
            return new PantheraMigrationDbContext(optionsBuilder.Options);
        }
    }
}

Now you can run migration commands using this project as a target/startup project, and migration files are created in this project instead of the data project. To run migration commands without source code, also check here.