設計階段 DbContext 建立Design-time DbContext Creation

有些 EF 工具命令需要在設計上建立的 DbContext 執行個體的時間 (例如,當執行移轉命令)。Some of the EF Tools commands require a DbContext instance to be created at design time (for example, when running Migrations commands). 有許多種,工具會嘗試建立它。There are various ways the tools try to create it.

從應用程式服務From application services

如果您的啟始專案的 ASP.NET Core 應用程式,工具會嘗試從應用程式的服務提供者取得 DbContext 物件。If your startup project is an ASP.NET Core app, the tools try to obtain the DbContext object from the application's service provider. 他們取得叫用Program.BuildWebHost()和存取IWebHost.Services屬性。They obtain it by invoking Program.BuildWebHost() and accessing the IWebHost.Services property. 使用註冊任何 DbContextIServiceCollection.AddDbContext<TContext>()可以找到並以此方式建立。Any DbContext registered using IServiceCollection.AddDbContext<TContext>() can be found and created this way. 此模式已ASP.NET Core 2.0 中導入This pattern was introduced in ASP.NET Core 2.0

使用預設建構函式Using the default constructor

如果無法從應用程式服務提供者取得 DbContext,工具會尋找專案內的 DbContext 類型。If the DbContext can't be obtained from the application service provider, the tools look for the DbContext type inside the project. 嘗試使用其預設建構函式加以建立。They try to create it using its default constructor.

從設計階段 factoryFrom a design-time factory

您也可以分辨工具如何實作來建立您的 DbContext IDesignTimeDbContextFactoryYou can also tell the tools how to create your DbContext by implementing IDesignTimeDbContextFactory. 如果您的專案內找到實作此介面的類別,則工具會略過之其他方式建立的 DbContext。If a class implementing this interface is found inside your project, the tools bypass the other ways of creating the DbContext. 它們一律會使用在設計階段的處理站。They always use the factory at design time. 此處理站是特別有用,如果您需要在執行階段,於設計階段的不同的方式設定 DbContext。A factory is especially useful if you need to configure the DbContext differently for design time than at runtime.

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;

namespace MyProject
{
    public class BloggingContextFactory : IDesignTimeDbContextFactory<BloggingContext>
    {
        public BloggingContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
            optionsBuilder.UseSqlite("Data Source=blog.db");

            return new BloggingContext(optionsBuilder.Options);
        }
    }
}

注意

args參數是目前未使用。The args parameter is currently unused. 沒有問題追蹤指定設計階段工具的引數的能力。There is an issue tracking the ability to specify design-time arguments from the tools.