使用個別的專案Using a Separate 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 haven't added any, add one to the DbContext project then move it.
  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>..\MyStarupProject\bin\$(Configuration)\</OutputPath>
      </PropertyGroup>
      

如果您所執行的所有項目正確,您應該能夠專案中加入新的移轉。If you did everything correctly, you should be able to add new migrations to the project.

Add-Migration NewMigration -Project MyApp.Migrations
dotnet ef migrations add NewMigration --project MyApp.Migrations