使用個別的遷移專案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. 這點很重要,因為如果遷移元件不包含現有的遷移,Add-Migration 命令將找不到 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