設定建立的 DbContextConfiguring a DbContext

本文將說明的設定模式DbContextDbContextOptionsThis article shows patterns for configuring a DbContext with DbContextOptions. 選項主要用來選取並設定資料存放區。Options are primarily used to select and configure the data store.

設定 DbContextOptionsConfiguring DbContextOptions

DbContext必須具有執行個體的DbContextOptions才能執行。DbContext must have an instance of DbContextOptions in order to execute. 這可以透過覆寫設定OnConfiguring,或從外部提供透過建構函式引數。This can be configured by overriding OnConfiguring, or supplied externally via a constructor argument.

如果同時使用OnConfiguring上提供選項,也就是說,它加總,而且可以執行覆寫建構函式的引數所提供的選項。If both are used, OnConfiguring is executed on the supplied options, meaning it is additive and can overwrite options supplied to the constructor argument.

建構函式引數Constructor argument

使用建構函式的內容程式碼Context code with constructor

public class BloggingContext : DbContext
{
    public BloggingContext(DbContextOptions<BloggingContext> options)
        : base(options)
    { }

    public DbSet<Blog> Blogs { get; set; }
}

提示

基底的 DbContext 建構函式也可接受的非泛型版本DbContextOptionsThe base constructor of DbContext also accepts the non-generic version of DbContextOptions. 有多個內容類型的應用程式,不建議使用非泛型版本。Using the non-generic version is not recommended for applications with multiple context types.

應用程式程式碼,以從建構函式引數初始化Application code to initialize from constructor argument

var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlite("Data Source=blog.db");

using (var context = new BloggingContext(optionsBuilder.Options))
{
  // do stuff
}

OnConfiguringOnConfiguring

警告

OnConfiguring上次發生,而且可以覆寫從 DI 或建構函式取得的選項。OnConfiguring occurs last and can overwrite options obtained from DI or the constructor. 這種方法本身就無法測試 (除非您的目標完整的資料庫)。This approach does not lend itself to testing (unless you target the full database).

內容的程式碼與OnConfiguring:Context code with OnConfiguring:

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Data Source=blog.db");
    }
}

應用程式程式碼以初始化OnConfiguring:Application code to initialize with OnConfiguring:

using (var context = new BloggingContext())
{
  // do stuff
}

使用相依性插入的 DbContextUsing DbContext with dependency injection

EF 支援使用DbContext與相依性插入容器。EF supports using DbContext with a dependency injection container. DbContext 類型可以使用新增至服務容器AddDbContext<TContext>Your DbContext type can be added to the service container by using AddDbContext<TContext>.

AddDbContext將這兩個您 DbContext 類型TContext,和DbContextOptions<TContext>適用於資料隱碼,從服務容器。AddDbContext will make both your DbContext type, TContext, and DbContextOptions<TContext> available for injection from the service container.

請參閱詳細閱讀下方的相依性插入的詳細資訊。See more reading below for information on dependency injection.

加入相依性插入的 dbcontextAdding dbcontext to dependency injection

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<BloggingContext>(options => options.UseSqlite("Data Source=blog.db"));
}

這需要將建構函式引數給 DbContext 類型可接受DbContextOptionsThis requires adding a constructor argument to your DbContext type that accepts DbContextOptions.

內容的程式碼:Context code:

public class BloggingContext : DbContext
{
    public BloggingContext(DbContextOptions<BloggingContext> options)
      :base(options)
    { }

    public DbSet<Blog> Blogs { get; set; }
}

(在 ASP.NET Core) 的應用程式程式碼:Application code (in ASP.NET Core):

public MyController(BloggingContext context)

(ServiceProvider 直接使用,較不常見) 的應用程式程式碼:Application code (using ServiceProvider directly, less common):

using (var context = serviceProvider.GetService<BloggingContext>())
{
  // do stuff
}

var options = serviceProvider.GetService<DbContextOptions<BloggingContext>>();

使用IDesignTimeDbContextFactory<TContext>Using IDesignTimeDbContextFactory<TContext>

上述選項的替代方案,您可能也提供的實作IDesignTimeDbContextFactory<TContext>As an alternative to the options above, you may also provide an implementation of IDesignTimeDbContextFactory<TContext>. EF 工具可以使用這個處理站,以建立您的 DbContext 執行個體。EF tools can use this factory to create an instance of your DbContext. 這可能需要以啟用特定的設計階段體驗,例如移轉。This may be required in order to enable specific design-time experiences such as migrations.

實作這個介面來啟用並沒有公用預設建構函式的內容類型的設計階段服務。Implement this interface to enable design-time services for context types that do not have a public default constructor. 設計階段服務會自動探索此介面衍生的內容相同的組件中的實作。Design-time services will automatically discover implementations of this interface that are in the same assembly as the derived context.

範例:Example:

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);
        }
    }
}

詳細閱讀More reading