設計階段服務

工具所使用的某些服務只會在設計階段使用。 這些服務會與 EF Core 的執行時間服務分開管理,以防止它們與您的應用程式一起部署。 若要覆寫其中一項服務(例如服務產生移轉檔案),請將 的 IDesignTimeServices 實作新增至您的啟始專案。

internal class MyDesignTimeServices : IDesignTimeServices
{
    public void ConfigureDesignTimeServices(IServiceCollection services)
        => services.AddSingleton<IMigrationsCodeGenerator, MyMigrationsCodeGenerator>();
}

參考 Microsoft.EntityFrameworkCore.Design

Microsoft.EntityFrameworkCore.Design 是 DevelopmentDependency 套件。 這表示相依性不會以可轉移方式流向其他專案,而且您預設無法參考其類型。

若要參考其類型並覆寫設計階段服務,請在專案檔中更新 PackageReference 專案的中繼資料。

<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.9">
  <PrivateAssets>all</PrivateAssets>
  <!-- Remove IncludeAssets to allow compiling against the assembly -->
  <!--<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>-->
</PackageReference>

如果封裝透過 Microsoft.EntityFrameworkCore.Tools 以可轉移方式參考,您必須將明確的 PackageReference 新增至套件,並變更其中繼資料。

服務清單

以下是設計階段服務的清單。

服務 描述
IAnnotationCodeGenerator 產生對應模型批註的程式碼。
ICSharpHelper 協助產生 C# 程式碼。
IPluralizer 複數和單數化單字。
IMigrationsCodeGenerator 產生移轉的程式碼。
IMigrationsScaffolder 管理移轉檔案的主要類別。
IDatabaseModelFactory 從資料庫建立資料庫模型。
IModelCodeGenerator 產生模型的程式碼。
IProviderConfigurationCodeGenerator 產生 OnConfiguring 程式碼。
IReverseEngineerScaffolder Scaffolding 反向工程模型的主要類別。
IScaffoldingModelFactory 從資料庫模型建立模型。

使用服務

這些服務也適用于建立您自己的工具。 例如,當您想要將設計階段工作流程的一部分自動化時。

您可以使用 AddEntityFrameworkDesignTimeServices 和 AddDbCoNtextDesignTimeServices 擴充方法來建置包含這些服務的服務提供者。

var db = new MyDbContext();

// Create design-time services
var serviceCollection = new ServiceCollection();
serviceCollection.AddEntityFrameworkDesignTimeServices();
serviceCollection.AddDbContextDesignTimeServices(db);
var serviceProvider = serviceCollection.BuildServiceProvider();

// Add a migration
var migrationsScaffolder = serviceProvider.GetService<IMigrationsScaffolder>();
var migration = migrationsScaffolder.ScaffoldMigration(migrationName, rootNamespace);
migrationsScaffolder.Save(projectDir, migration, outputDir);