使用個別的專案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 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.

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