使用单独的迁移项目Using a Separate Migrations Project

你可能想要将迁移存储在与包含你的不同的程序集中 DbContextYou may want to store your migrations in a different assembly than the one containing your DbContext. 你还可以使用此策略来维护多个迁移集,例如,一个用于开发,另一个用于发布到发布升级。You can also use this strategy to maintain multiple sets of migrations, for example, one for development and another for release-to-release upgrades.

若要执行此操作...To do this...

  1. 创建一个新的类库。Create a new class library.

  2. 添加对 DbContext 程序集的引用。Add a reference to your DbContext assembly.

  3. 将迁移和模型快照文件移动到类库。Move the migrations and model snapshot files to the class library.

    提示

    如果没有现有迁移,请在包含 DbContext 的项目中生成一个迁移,然后移动它。If you have no existing migrations, generate one in the project containing the DbContext then move it. 这一点很重要,因为如果迁移程序集不包含现有迁移,则添加迁移命令将无法找到 DbContext。This is important because if the migrations assembly does not contain an existing migration, the Add-Migration command will be unable to find the DbContext.

  4. 配置迁移程序集:Configure the migrations assembly:

    options.UseSqlServer(
        connectionString,
        x => x.MigrationsAssembly("MyApp.Migrations"));
    
  5. 从启动程序集添加对迁移程序集的引用。Add a reference to your migrations assembly from the startup assembly.

    • 如果这导致循环依赖项,请更新类库的输出路径:If this causes a circular dependency, update the output path of the class library:

      <PropertyGroup>
        <OutputPath>..\MyStartupProject\bin\$(Configuration)\</OutputPath>
      </PropertyGroup>
      

如果一切正常,应能够向项目添加新的迁移。If you did everything correctly, you should be able to add new migrations to the project.

dotnet ef migrations add NewMigration --project MyApp.Migrations