EntityFramework Core: Generate Migration Scripts in a Separate Project

Raymond Tang Raymond Tang 0 867 0.61 index 5/15/2021

In entity-framework code-first solution, we usually generate migrations scripts in the default startup project. For instance, for ASP.NET Core applications, the scripts can be generated in Migrationsfolder of the web application project. This articles shows an approach to generate migration scripts in a separate project.

Scenario

Assuming the following solution setup:

sln
      WebProject
      DataModels
      Migrations

In solution folder sln, there are three projects:

  • WebProject: ASP.NET Core web application project.
  • DataModels: all the entity framework models and application DbContextclasses are defined here.
  • Migrations: all the migration scripts.

The task is to generate migration scripts in Migrationsproject folder.

Resolution

The following steps provide one solution to implement the above task.

  1. Open Command Prompt (Windows) or Terminal (Linux).

  2. Change current folder to sln:

    cd sln
    
  3. Add initial migration script:

    dotnet ef migrations add InitMigrations --startup-project WebProject
    

    The above command will generate initial migration scripts by default in WebProject. The startup project is set as WebProject.

  4. Create Migrationsproject as a C# library project with all the necessary references to entity framework package and DataModelsproject.

  5. Move the generated scripts to project Migrationsmanually.

  6. Generate new migrations using the following command ongoing forward:

    dotnet ef migrations add MyNewMigration --startup-project WebProject --project Migrations
    

References

Using a Separate Migrations Project - EF Core | Microsoft Docs

.net dotnetcore entity-framework

Join the Discussion

View or add your thoughts below

Comments