Skip to content

Commit ad30a81

Browse files
Merge pull request #5227 from dotnet/main
Auto Publish – main to live - 2026-01-06 23:03 UTC
2 parents 8b52714 + 0a616a9 commit ad30a81

18 files changed

Lines changed: 431 additions & 77 deletions

File tree

entity-framework/core/dbcontext-configuration/index.md

Lines changed: 74 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,8 +90,6 @@ The final result is an `ApplicationDbContext` instance created for each request
9090

9191
Read further in this article to learn more about configuration options. See [Dependency injection in ASP.NET Core](/aspnet/core/fundamentals/dependency-injection) for more information.
9292

93-
<!-- See also [Using Dependency Injection](TODO) for advanced dependency injection configuration with EF Core. -->
94-
9593
## Basic DbContext initialization with 'new'
9694

9795
`DbContext` instances can be constructed with `new` in C#. Configuration can be performed by overriding the `OnConfiguring` method, or by passing options to the constructor. For example:
@@ -425,6 +423,80 @@ Any code that explicitly executes multiple threads in parallel should ensure tha
425423

426424
Using dependency injection, this can be achieved by either registering the context as scoped, and creating scopes (using `IServiceScopeFactory`) for each thread, or by registering the `DbContext` as transient (using the overload of `AddDbContext` which takes a `ServiceLifetime` parameter).
427425

426+
<a name="configuredbcontext"></a>
427+
428+
## ConfigureDbContext for configuration composition
429+
430+
> [!NOTE]
431+
> This section covers intermediate-level usage of EF Core primarily intended for reusable libraries and components. Most applications should use the `AddDbContextFactory` pattern described earlier in this article.
432+
433+
Starting with EF Core 9.0, you can use <xref:Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.ConfigureDbContext*> to apply additional configuration to a `DbContext` either before or after the `AddDbContext` call. This is particularly useful for composing non-conflicting configuration in reusable components or tests.
434+
435+
### Basic ConfigureDbContext usage
436+
437+
`ConfigureDbContext` allows you to add configuration in a reusable library or component without replacing the entire provider configuration:
438+
439+
<!--
440+
var services = new ServiceCollection();
441+
442+
services.ConfigureDbContext<BlogContext>(options =>
443+
options.EnableSensitiveDataLogging()
444+
.EnableDetailedErrors());
445+
446+
services.AddDbContext<BlogContext>(options =>
447+
options.UseInMemoryDatabase("BasicExample"));
448+
449+
var serviceProvider = services.BuildServiceProvider();
450+
-->
451+
[!code-csharp[BasicConfigureDbContext](../../../samples/core/Miscellaneous/ConfiguringDbContext/ConfigureDbContextSample.cs?name=BasicConfigureDbContext)]
452+
453+
### Provider-specific configuration without connection strings
454+
455+
To apply provider-specific configuration you can use provider-specific configuration methods without supplying the connection string. The SQL Server provider also includes `ConfigureSqlEngine` for this case. See [SQL Server-specific batching behavior](xref:core/providers/sql-server/misc#configuresqlengine) for more information.
456+
457+
<!--
458+
var services = new ServiceCollection();
459+
460+
services.ConfigureDbContext<BlogContext>(options =>
461+
options.UseSqlServer(sqlOptions =>
462+
sqlOptions.EnableRetryOnFailure()));
463+
464+
services.AddDbContext<BlogContext>(options =>
465+
options.UseSqlServer("connectionString"));
466+
467+
var serviceProvider = services.BuildServiceProvider();
468+
-->
469+
[!code-csharp[ProviderSpecificConfiguration](../../../samples/core/Miscellaneous/ConfiguringDbContext/ConfigureDbContextSample.cs?name=ProviderSpecificConfiguration)]
470+
471+
### ConfigureDbContext and AddDbContext precedence
472+
473+
When both `ConfigureDbContext` and `AddDbContext` are used, or when multiple calls to these methods are made, the configuration is applied in the order the methods are called, with later calls taking precedence for conflicting options.
474+
475+
For non-conflicting options (like adding logging, interceptors, or other settings), all configurations are composed together:
476+
477+
<!--
478+
var services = new ServiceCollection();
479+
480+
services.ConfigureDbContext<BlogContext>(options =>
481+
options.LogTo(Console.WriteLine));
482+
483+
services.AddDbContext<BlogContext>(options =>
484+
options.UseInMemoryDatabase("CompositionExample"));
485+
486+
services.ConfigureDbContext<BlogContext>(options =>
487+
options.EnableSensitiveDataLogging());
488+
489+
var serviceProvider = services.BuildServiceProvider();
490+
-->
491+
[!code-csharp[ConfigurationComposition](../../../samples/core/Miscellaneous/ConfiguringDbContext/ConfigureDbContextSample.cs?name=ConfigurationComposition)]
492+
493+
For conflicting options, the last configuration wins. See [breaking changes in EF Core 8.0](xref:core/what-is-new/ef-core-8.0/breaking-changes#AddDbContext) for more information about this behavior change.
494+
495+
> [!NOTE]
496+
> Configuring a different provider will not remove the previous provider configuration. This can lead to errors when creating the context. To completely replace the provider, you need to remove the context registration and re-add it, or create a new service collection.
497+
498+
<!-- See also [Using Dependency Injection](TODO) for advanced dependency injection configuration with EF Core. -->
499+
428500
## More reading
429501

430502
- Read [Dependency Injection](/aspnet/core/fundamentals/dependency-injection) to learn more about using DI.

entity-framework/core/modeling/data-seeding.md

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -21,25 +21,25 @@ There are several ways this can be accomplished in EF Core:
2121

2222
## Configuration options `UseSeeding` and `UseAsyncSeeding` methods
2323

24-
EF 9 introduced `UseSeeding` and `UseAsyncSeeding` methods, which provide a convenient way of seeding the database with initial data. These methods aim to improve the experience of using custom initialization logic (explained below). They provide one clear location where all the data seeding code can be placed. Moreover, the code inside `UseSeeding` and `UseAsyncSeeding` methods is protected by the [migration locking mechanism](/ef/core/what-is-new/ef-core-9.0/whatsnew#concurrent-migrations) to prevent concurrency issues.
24+
EF 9 introduced <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseSeeding*> and <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseAsyncSeeding*> methods, which provide a convenient way of seeding the database with initial data. These methods aim to improve the experience of using custom initialization logic (explained below). They provide one clear location where all the data seeding code can be placed. Moreover, the code inside <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseSeeding*> and <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseAsyncSeeding*> methods is protected by the [migration locking mechanism](/ef/core/what-is-new/ef-core-9.0/whatsnew#concurrent-migrations) to prevent concurrency issues.
2525

26-
The new seeding methods are called as part of [`EnsureCreated`](xref:Microsoft.EntityFrameworkCore.Storage.IDatabaseCreator.EnsureCreated) operation, [`Migrate`](/dotnet/api/microsoft.entityframeworkcore.relationaldatabasefacadeextensions.migrate) and `dotnet ef database update` command, even if there are no model changes and no migrations were applied.
26+
The new seeding methods are called as part of <xref:Microsoft.EntityFrameworkCore.Storage.IDatabaseCreator.EnsureCreated*> operation, <xref:Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate*> and `dotnet ef database update` command, even if there are no model changes and no migrations were applied.
2727

2828
> [!TIP]
29-
> Using `UseSeeding` and `UseAsyncSeeding` is the recommended way of seeding the database with initial data when working with EF Core.
29+
> Using <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseSeeding*> and <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseAsyncSeeding*> is the recommended way of seeding the database with initial data when working with EF Core.
3030
3131
These methods can be set up in the [options configuration step](/ef/core/dbcontext-configuration/#dbcontextoptions). Here is an example:
3232

3333
[!code-csharp[ContextOptionSeeding](../../../samples/core/Modeling/DataSeeding/DataSeedingContext.cs?name=ContextOptionSeeding)]
3434

3535
> [!NOTE]
36-
> `UseSeeding` is called from the `EnsureCreated` method, and `UseAsyncSeeding` is called from the `EnsureCreatedAsync` method. When using this feature, it is recommended to implement both `UseSeeding` and `UseAsyncSeeding` methods using similar logic, even if the code using EF is asynchronous. EF Core tooling currently relies on the synchronous version of the method and will not seed the database correctly if the `UseSeeding` method is not implemented.
36+
> <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseSeeding*> is called from the <xref:Microsoft.EntityFrameworkCore.Storage.IDatabaseCreator.EnsureCreated*> method, and <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseAsyncSeeding*> is called from the <xref:Microsoft.EntityFrameworkCore.Storage.IDatabaseCreator.EnsureCreatedAsync*> method. When using this feature, it is recommended to implement both <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseSeeding*> and <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseAsyncSeeding*> methods using similar logic, even if the code using EF is asynchronous. EF Core tooling currently relies on the synchronous version of the method and will not seed the database correctly if the <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseSeeding*> method is not implemented.
3737
3838
<a name="custom-initialization-logic"></a>
3939

4040
## Custom initialization logic
4141

42-
A straightforward and powerful way to perform data seeding is to use [`DbContext.SaveChangesAsync()`](xref:core/saving/index) before the main application logic begins execution. It is recommended to use `UseSeeding` and `UseAsyncSeeding` for that purpose, however sometimes using these methods is not a good solution. An example scenario is when seeding requires using two different contexts in one transaction. Below is a code sample performing custom initialization in the application directly:
42+
A straightforward and powerful way to perform data seeding is to use <xref:Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync*> before the main application logic begins execution. It is recommended to use <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseSeeding*> and <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseAsyncSeeding*> for that purpose, however sometimes using these methods is not a good solution. An example scenario is when seeding requires using two different contexts in one transaction. Below is a code sample performing custom initialization in the application directly:
4343

4444
[!code-csharp[Main](../../../samples/core/Modeling/DataSeeding/Program.cs?name=CustomSeeding)]
4545

@@ -85,10 +85,10 @@ Once the data has been added to the model, [migrations](xref:core/managing-schem
8585
> [!TIP]
8686
> If you need to apply migrations as part of an automated deployment you can [create a SQL script](xref:core/managing-schemas/migrations/applying#sql-scripts) that can be previewed before execution.
8787
88-
Alternatively, you can use `context.Database.EnsureCreatedAsync()` to create a new database containing the managed data, for example for a test database or when using the in-memory provider or any non-relational database. Note that if the database already exists, `EnsureCreatedAsync()` will neither update the schema nor managed data in the database. For relational databases you shouldn't call `EnsureCreatedAsync()` if you plan to use Migrations.
88+
Alternatively, you can use <xref:Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.EnsureCreatedAsync*> to create a new database containing the managed data, for example for a test database or when using the in-memory provider or any non-relational database. Note that if the database already exists, <xref:Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.EnsureCreatedAsync*> will neither update the schema nor managed data in the database. For relational databases you shouldn't call <xref:Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.EnsureCreatedAsync*> if you plan to use Migrations.
8989

9090
> [!NOTE]
91-
> Populating the database using the `HasData` method used to be referred to as "data seeding". This naming sets incorrect expectations, as the feature has a number of limitations and is only appropriate for specific types of data. That is why we decided to rename it to "model managed data". `UseSeeding` and `UseAsyncSeeding` methods should be used for general purpose data seeding.
91+
> Populating the database using the <xref:Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder`1.HasData*> method used to be referred to as "data seeding". This naming sets incorrect expectations, as the feature has a number of limitations and is only appropriate for specific types of data. That is why we decided to rename it to "model managed data". <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseSeeding*> and <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseAsyncSeeding*> methods should be used for general purpose data seeding.
9292
9393
### Limitations of model managed data
9494

@@ -99,7 +99,7 @@ This type of data is managed by migrations and the script to update the data tha
9999

100100
Therefore this feature is most useful for static data that's not expected to change outside of migrations and does not depend on anything else in the database, for example ZIP codes.
101101

102-
If your scenario includes any of the following it is recommended to use `UseSeeding` and `UseAsyncSeeding` methods described in the first section:
102+
If your scenario includes any of the following it is recommended to use <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseSeeding*> and <xref:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseAsyncSeeding*> methods described in the first section:
103103

104104
* Temporary data for testing
105105
* Data that depends on database state
@@ -113,6 +113,6 @@ If your scenario includes any of the following it is recommended to use `UseSeed
113113

114114
## Manual migration customization
115115

116-
When a migration is added the changes to the data specified with `HasData` are transformed to calls to `InsertData()`, `UpdateData()`, and `DeleteData()`. One way of working around some of the limitations of `HasData` is to manually add these calls or [custom operations](xref:core/managing-schemas/migrations/operations) to the migration instead.
116+
When a migration is added the changes to the data specified with <xref:Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder`1.HasData*> are transformed to calls to `InsertData()`, `UpdateData()`, and `DeleteData()`. One way of working around some of the limitations of <xref:Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder`1.HasData*> is to manually add these calls or [custom operations](xref:core/managing-schemas/migrations/operations) to the migration instead.
117117

118118
[!code-csharp[CustomInsert](../../../samples/core/Modeling/DataSeeding/Migrations/20241016041555_Initial.cs?name=CustomInsert)]

0 commit comments

Comments
 (0)