使用獨立遷移專案

你可以將遷移資料存放在與包含你 DbContext. 的專案不同的專案中。 當應用程式專案具有特定平台性,如 WinUI、.NET MAUI、Blazor WebAssembly 或 Azure Functions,或針對特定執行時識別碼(RID)時,建議使用此方法。 它也可以用來維護多組遷移。

Tip

您可以在GitHub觀看本文的樣本。

專案版面配置

範例使用三個專案:

計畫 責任 References
WebApplication1.Data 擁有 DbContext 實體類型 EF Core 供應商
WebApplication1.Migrations 擁有遷移、模型快照及設計時上下文建立 資料專案、EF Core 提供者,以及 Microsoft.EntityFrameworkCore.Design
WebApplication1 執行應用程式 資料專案與遷移專案

應用程式在執行時發現或套用遷移時,例如呼叫 Migrate,需要對遷移專案的參考。 如果遷移只由部署產物套用,且應用程式從未載入遷移,則不需要該參考。

配置專案

  1. 建立一個類別函式庫用於遷移,並新增包含 DbContext的專案參考。

  2. 新增資料庫提供者 和 Microsoft.EntityFrameworkCore.Design 遷移專案。 將設計套件標記為私人開發依賴:

    <ItemGroup>
      <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="...">
        <PrivateAssets>all</PrivateAssets>
        <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      </PackageReference>
      <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="..." />
    </ItemGroup>
    
    <ItemGroup>
      <ProjectReference Include="..\WebApplication1.Data\WebApplication1.Data.csproj" />
    </ItemGroup>
    
  3. 在遷移專案中實作 IDesignTimeDbContextFactory<TContext> 。 工廠允許工具在不執行應用程式專案的情況下建立上下文:

    public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
    {
        public ApplicationDbContext CreateDbContext(string[] args)
        {
            var connectionString = args.FirstOrDefault()
                ?? @"Server=(localdb)\mssqllocaldb;Database=WebApplication1;Trusted_Connection=True";
    
            var options = new DbContextOptionsBuilder<ApplicationDbContext>()
                .UseSqlServer(
                    connectionString,
                    sqlServer => sqlServer.MigrationsAssembly(typeof(ApplicationDbContextFactory).Assembly.GetName().Name))
                .Options;
    
            return new ApplicationDbContext(options);
        }
    }
    

    保持設計時的提供者與模型配置與執行時配置一致。 範例接受可選的 連接字串 參數,當未提供參數時則使用本地開發連線。

  4. 在執行時註冊上下文時,請設定遷移組件:

    services.AddDbContext<ApplicationDbContext>(
        options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection"),
                x => x.MigrationsAssembly("WebApplication1.Migrations")));
    
  5. 如果應用程式在執行時套用遷移或以其他方式發現遷移,請從應用程式中向遷移專案新增一個正常的參考:

    <ItemGroup>
      <ProjectReference Include="..\WebApplication1.Migrations\WebApplication1.Migrations.csproj" />
    </ItemGroup>
    

    資料專案不得參考遷移專案。 這會造成循環依賴,因為遷移專案已經參考了資料專案。

  6. 若已存在遷移,將所有遷移檔案與模型快照移至遷移專案並更新其命名空間。 當沒有現有遷移時,設計時工廠允許在遷移專案中直接建立初始遷移。

使用工具

將遷移專案同時作為 目標專案和啟動專案。 目標專案會接收產生的檔案,而啟動專案則由工具建立並執行。 在此版面中,使用遷移專案同時執行應用程式啟動程式碼,防止工具執行應用程式啟動程式碼。

從解決方案目錄執行以下指令:

dotnet ef migrations add NewMigration \
    --project WebApplication1.Migrations \
    --startup-project WebApplication1.Migrations

相同的專案選項也適用於其他指令:

dotnet ef migrations list \
    --project WebApplication1.Migrations \
    --startup-project WebApplication1.Migrations

dotnet ef migrations script --output artifacts/migrations.sql \
    --project WebApplication1.Migrations \
    --startup-project WebApplication1.Migrations

dotnet ef migrations bundle --output artifacts/efbundle \
    --project WebApplication1.Migrations \
    --startup-project WebApplication1.Migrations

從 EF Core 11 開始,重複的專案選項可以儲存在 .config/dotnet-ef.json。

在執行帶有 --no-build的指令之前,或在其他程序消耗輸出之前,先建置遷移專案。 一般 dotnet ef 指令會自動建置目標專案和啟動專案。

平台專屬應用

不要把特定平台的應用程式專案當作 EF 工具的啟動專案。 行動裝置、瀏覽器、桌面、功能及 RID 專屬專案可能需要無法執行的工作負載或原生主機 dotnet ef 。 從 EF Core 11 開始,工具會在使用特定平台的啟動專案時發出警告。

請使用上述配置來處理 .NET MAUI、WinUI、Blazor WebAssembly、Azure Functions 及類似應用程式:

  1. 將上下文和實體類型放入共享資料專案中。
  2. 把遷移IDesignTimeDbContextFactory<TContext>和放進一般跨平台的 .NET 專案。
  3. 將遷移專案作為目標和啟動專案來執行這些工具。
  4. 只有當應用程式在執行時載入或套用遷移時,才從應用程式中引用遷移專案。

目前不計畫直接支援 Xamarin 與 MAUI 平台專案;詳見 dotnet/efcore#7152。 Xamarin 應用程式應先升級至 .NET MAUI。

流程架構

執行工具的流程必須能夠載入每一個設計時組件。 64 位元 Visual Studio 或 .NET 程序無法載入僅支援 x86 的啟動組件,Arm64 及其他架構也有同樣的限制。 我比較喜歡 AnyCPU 的遷移專案。 若設計時相依需要特定架構,則明確呼叫對應的 .NET SDK。

設計時流程架構與部署目標是分開的。 建立套件時,請使用 --target-runtime 或 -TargetRuntime 產生部署RID的產物,例如 linux-arm64 或 osx-arm64。