設定建立的 DbContextConfiguring a DbContext

本文示範基本模式設定DbContext透過DbContextOptions連接到資料庫,使用特定的 EF 核心提供者和選擇性的行為。This article shows basic patterns for configuring a DbContext via a DbContextOptions to connect to a database using a specific EF Core provider and optional behaviors.

設計階段 DbContext 組態Design-time DbContext configuration

EF 核心設計階段工具,例如移轉必須能夠探索和建立的工作執行個體DbContext從中收集有關應用程式的實體類型和它們如何對應到資料庫結構描述的詳細資料的類型。EF Core design-time tools such as migrations need to be able to discover and create a working instance of a DbContext type in order to gather details about the application's entity types and how they map to a database schema. 只要可以輕鬆地建立此工具,此程序可能會自動DbContext的方式,它將會設定同樣的方式就會設定在執行階段。This process can be automatic as long as the tool can easily create the DbContext in such a way that it will be configured similarly to how it would be configured at run-time.

同時提供必要的組態資訊的任何模式DbContext可在執行階段,需要使用的工具DbContext在設計階段只能處理有限數目的模式。While any pattern that provides the necessary configuration information to the DbContext can work at run-time, tools that require using a DbContext at design-time can only work with a limited number of patterns. 中詳細說明這些先決條件設計階段內容建立> 一節。These are covered in more detail in the Design-Time Context Creation section.

設定 DbContextOptionsConfiguring DbContextOptions

DbContext 必須具有執行個體的DbContextOptions才能執行任何工作。DbContext must have an instance of DbContextOptions in order to perform any work. DbContextOptions這類執行個體帶有的組態資訊:The DbContextOptions instance carries configuration information such as:

  • 若要使用,資料庫提供者通常會選取叫用方法時,例如UseSqlServerUseSqliteThe database provider to use, typically selected by invoking a method such as UseSqlServer or UseSqlite
  • 任何必要的連接字串或資料庫執行個體識別項通常傳遞做為引數給上述提供者選取方法Any necessary connection string or identifier of the database instance, typically passed as an argument to the provider selection method mentioned above
  • 所有的提供者層級時的選擇性行為選取器,通常也會在提供者選取方法的呼叫鏈結Any provider-level optional behavior selectors, typically also chained inside the call to the provider selection method
  • 所有一般 EF 核心行為的選取器,通常鏈結提供者選取器方法之前或之後Any general EF Core behavior selectors, typically chained after or before the provider selector method

下列範例會設定DbContextOptions若要使用 SQL Server 提供者,連接中所包含connectionString變數、 提供者層級命令逾時和 EF 核心行為選取器,讓執行中的所有查詢DbContext否追蹤預設:The following example configures the DbContextOptions to use the SQL Server provider, a connection contained in the connectionString variable, a provider-level command timeout, and an EF Core behavior selector that makes all queries executed in the DbContext no-tracking by default:

optionsBuilder
    .UseSqlServer(connectionString, providerOptions=>providerOptions.CommandTimeout(60))
    .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);

注意

提供者選取器方法,以及先前所述的其他行為選取器方法是擴充方法上DbContextOptions或提供者特有的選項類別。Provider selector methods and other behavior selector methods mentioned above are extension methods on DbContextOptions or provider-specific option classes. 才能存取這些擴充方法,您可能需要有命名空間 (通常Microsoft.EntityFrameworkCore) 在範圍內,以及包含在專案的其他套件相依性。In order to have access to these extension methods you may need to have a namespace (typically Microsoft.EntityFrameworkCore) in scope and include additional package dependencies in the project.

DbContextOptions可以提供給DbContext藉由覆寫OnConfiguring方法,或從外部透過建構函式引數。The DbContextOptions can be supplied to the DbContext by overriding the OnConfiguring method or externally via a constructor argument.

如果同時使用OnConfiguring會最後套用,而且可以覆寫建構函式的引數所提供的選項。If both are used, OnConfiguring is applied last 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 建構函式也可接受的非泛型版本DbContextOptions,但有多個內容類型的應用程式不建議使用非泛型版本。The base constructor of DbContext also accepts the non-generic version of DbContextOptions, but 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: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");
    }
}

應用程式程式碼以初始化DbContext使用OnConfiguring:Application code to initialize a DbContext that uses OnConfiguring:

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

提示

這種方法本身就無法進行測試,除非測試目標的完整的資料庫。This approach does not lend itself to testing, unless the tests target the full database.

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

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

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

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

加入Dbcontext相依性插入至:Adding the Dbcontext to dependency injection:

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

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

內容的程式碼: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 class MyController
{
    private readonly BloggingContext _context;

    public MyController(BloggingContext context)
    {
      _context = context;
    }

    ...
}

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

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

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

詳細閱讀More reading