Class DbContextOptionsBuilder
- Namespace
- Microsoft.EntityFrameworkCore
- Assembly
- Microsoft.EntityFrameworkCore.dll
Provides a simple API surface for configuring DbContextOptions. Databases (and other extensions) typically define extension methods on this object that allow you to configure the database connection (and other options) to be used for a context.
public class DbContextOptionsBuilder : IDbContextOptionsBuilderInfrastructure
- Inheritance
-
DbContextOptionsBuilder
- Implements
- Derived
- Inherited Members
Remarks
You can use DbContextOptionsBuilder to configure a context by overriding OnConfiguring(DbContextOptionsBuilder) or creating a DbContextOptions externally and passing it to the context constructor.
See Using DbContextOptions for more information and examples.
Constructors
DbContextOptionsBuilder()
Initializes a new instance of the DbContextOptionsBuilder class with no options set.
public DbContextOptionsBuilder()
DbContextOptionsBuilder(DbContextOptions)
Initializes a new instance of the DbContextOptionsBuilder class to further configure a given DbContextOptions.
public DbContextOptionsBuilder(DbContextOptions options)
Parameters
options
DbContextOptionsThe options to be configured.
Properties
IsConfigured
Gets a value indicating whether any options have been configured.
public virtual bool IsConfigured { get; }
Property Value
Remarks
This can be useful when you have overridden OnConfiguring(DbContextOptionsBuilder) to configure the context, but in some cases you also externally provide options via the context constructor. This property can be used to determine if the options have already been set, and skip some or all of the logic in OnConfiguring(DbContextOptionsBuilder).
Options
Gets the options being configured.
public virtual DbContextOptions Options { get; }
Property Value
Methods
AddInterceptors(params IInterceptor[])
Adds IInterceptor instances to those registered on the context.
public virtual DbContextOptionsBuilder AddInterceptors(params IInterceptor[] interceptors)
Parameters
interceptors
IInterceptor[]The interceptors to add.
Returns
- DbContextOptionsBuilder
The same builder instance so that multiple calls can be chained.
Remarks
Interceptors can be used to view, change, or suppress operations taken by Entity Framework. See the specific implementations of IInterceptor for details. For example, 'IDbCommandInterceptor'.
Extensions can also register multiple IInterceptors in the internal service provider. If both injected and application interceptors are found, then the injected interceptors are run in the order that they are resolved from the service provider, and then the application interceptors are run in the order that they were added to the context.
Calling this method multiple times will result in all interceptors in every call being added to the context. Interceptors added in a previous call are not overridden by interceptors added in a later call.
See Using DbContextOptions and EF Core interceptors for more information and examples.
AddInterceptors(IEnumerable<IInterceptor>)
Adds IInterceptor instances to those registered on the context.
public virtual DbContextOptionsBuilder AddInterceptors(IEnumerable<IInterceptor> interceptors)
Parameters
interceptors
IEnumerable<IInterceptor>The interceptors to add.
Returns
- DbContextOptionsBuilder
The same builder instance so that multiple calls can be chained.
Remarks
Interceptors can be used to view, change, or suppress operations taken by Entity Framework. See the specific implementations of IInterceptor for details. For example, 'IDbCommandInterceptor'.
A single interceptor instance can implement multiple different interceptor interfaces. It will be registered as an interceptor for all interfaces that it implements.
Extensions can also register multiple IInterceptors in the internal service provider. If both injected and application interceptors are found, then the injected interceptors are run in the order that they are resolved from the service provider, and then the application interceptors are run in the order that they were added to the context.
Calling this method multiple times will result in all interceptors in every call being added to the context. Interceptors added in a previous call are not overridden by interceptors added in a later call.
See Using DbContextOptions and EF Core interceptors for more information and examples.
ConfigureLoggingCacheTime(TimeSpan)
Configures how long EF Core will cache logging configuration in certain high-performance paths. This makes EF Core skip potentially costly logging checks, but means that runtime logging changes (e.g. registering a new DiagnosticListener may not be taken into account right away).
public virtual DbContextOptionsBuilder ConfigureLoggingCacheTime(TimeSpan timeSpan)
Parameters
timeSpan
TimeSpanThe maximum time period over which to skip logging checks before checking again.
Returns
- DbContextOptionsBuilder
The same builder instance so that multiple calls can be chained.
Remarks
Defaults to one second.
See Using DbContextOptions and Logging for more information and examples.
ConfigureWarnings(Action<WarningsConfigurationBuilder>)
Configures the runtime behavior of warnings generated by Entity Framework. You can set a default behavior and behaviors for each warning type.
public virtual DbContextOptionsBuilder ConfigureWarnings(Action<WarningsConfigurationBuilder> warningsConfigurationBuilderAction)
Parameters
warningsConfigurationBuilderAction
Action<WarningsConfigurationBuilder>An action to configure the warning behavior.
Returns
- DbContextOptionsBuilder
The same builder instance so that multiple calls can be chained.
Remarks
Note that changing this configuration can cause EF to build a new internal service provider, which may cause issues with performance. Generally it is expected that no more than one or two different configurations will be used for a given application.
Note that if the application is setting the internal service provider through a call to UseInternalServiceProvider(IServiceProvider?), then this option must configured the same way for all uses of that service provider. Consider instead not calling UseInternalServiceProvider(IServiceProvider?) so that EF will manage the service providers and can create new instances as required.
See Using DbContextOptions and Logging for more information and examples.
EnableDetailedErrors(bool)
Enables detailed errors when handling of data value exceptions that occur during processing of store query results. Such errors most often occur due to misconfiguration of entity properties. E.g. If a property is configured to be of type 'int', but the underlying data in the store is actually of type 'string', then an exception will be generated at runtime during processing of the data value. When this option is enabled and a data error is encountered, the generated exception will include details of the specific entity property that generated the error.
public virtual DbContextOptionsBuilder EnableDetailedErrors(bool detailedErrorsEnabled = true)
Parameters
detailedErrorsEnabled
bool
Returns
- DbContextOptionsBuilder
The same builder instance so that multiple calls can be chained.
Remarks
Enabling this option incurs a small performance overhead during query execution.
Note that if the application is setting the internal service provider through a call to UseInternalServiceProvider(IServiceProvider?), then this option must configured the same way for all uses of that service provider. Consider instead not calling UseInternalServiceProvider(IServiceProvider?) so that EF will manage the service providers and can create new instances as required.
See Using DbContextOptions and Logging for more information and examples.
EnableSensitiveDataLogging(bool)
Enables application data to be included in exception messages, logging, etc. This can include the values assigned to properties of your entity instances, parameter values for commands being sent to the database, and other such data. You should only enable this flag if you have the appropriate security measures in place based on the sensitivity of this data.
public virtual DbContextOptionsBuilder EnableSensitiveDataLogging(bool sensitiveDataLoggingEnabled = true)
Parameters
Returns
- DbContextOptionsBuilder
The same builder instance so that multiple calls can be chained.
Remarks
Note that if the application is setting the internal service provider through a call to UseInternalServiceProvider(IServiceProvider?), then this option must configured the same way for all uses of that service provider. Consider instead not calling UseInternalServiceProvider(IServiceProvider?) so that EF will manage the service providers and can create new instances as required.
See Using DbContextOptions and Logging for more information and examples.
EnableServiceProviderCaching(bool)
Enables or disables caching of internal service providers. Disabling caching can massively impact performance and should only be used in testing scenarios that build many service providers for test isolation.
public virtual DbContextOptionsBuilder EnableServiceProviderCaching(bool cacheServiceProvider = true)
Parameters
Returns
- DbContextOptionsBuilder
The same builder instance so that multiple calls can be chained.
Remarks
Note that if the application is setting the internal service provider through a call to UseInternalServiceProvider(IServiceProvider?), then setting this option will have no effect.
See Using DbContextOptions for more information and examples.
EnableThreadSafetyChecks(bool)
Disables concurrency detection, which detects many cases of erroneous concurrent usage of a DbContext instance and causes an informative exception to be thrown. This provides a minor performance improvement, but if a DbContext instance is used concurrently, the behavior will be undefined and the program may fail in unpredictable ways.
public virtual DbContextOptionsBuilder EnableThreadSafetyChecks(bool enableChecks = true)
Parameters
enableChecks
bool
Returns
- DbContextOptionsBuilder
The same builder instance so that multiple calls can be chained.
Remarks
Only disable concurrency detection after confirming that the performance gains are considerable, and the application has been thoroughly tested against concurrency bugs.
Note that if the application is setting the internal service provider through a call to UseInternalServiceProvider(IServiceProvider?), then this option must configured the same way for all uses of that service provider. Consider instead not calling UseInternalServiceProvider(IServiceProvider?) so that EF will manage the service providers and can create new instances as required.
See Using DbContextOptions for more information and examples.
LogTo(Action<string>, LogLevel, DbContextLoggerOptions?)
Logs using the supplied action. For example, use optionsBuilder.LogTo(Console.WriteLine)
to
log to the console.
public virtual DbContextOptionsBuilder LogTo(Action<string> action, LogLevel minimumLevel = LogLevel.Debug, DbContextLoggerOptions? options = null)
Parameters
action
Action<string>Delegate called when there is a message to log.
minimumLevel
LogLevelThe minimum level of logging event to log. Defaults to Debug
options
DbContextLoggerOptions?Formatting options for log messages. Passing null (the default) means use DefaultWithLocalTime
Returns
- DbContextOptionsBuilder
The same builder instance so that multiple calls can be chained.
Remarks
This overload allows the minimum level of logging and the log formatting to be controlled. Use the LogTo(Action<string>, IEnumerable<EventId>, LogLevel, DbContextLoggerOptions?) overload to log only specific events. Use the LogTo(Action<string>, IEnumerable<string>, LogLevel, DbContextLoggerOptions?) overload to log only events in specific categories. Use the LogTo(Action<string>, Func<EventId, LogLevel, bool>, DbContextLoggerOptions?) overload to use a custom filter for events. Use the LogTo(Func<EventId, LogLevel, bool>, Action<EventData>) overload to log to a fully custom logger.
See Using DbContextOptions and Logging for more information and examples.
LogTo(Action<string>, IEnumerable<EventId>, LogLevel, DbContextLoggerOptions?)
Logs the specified events using the supplied action. For example, use
optionsBuilder.LogTo(Console.WriteLine, new[] { CoreEventId.ContextInitialized })
to log the
ContextInitialized event to the console.
public virtual DbContextOptionsBuilder LogTo(Action<string> action, IEnumerable<EventId> events, LogLevel minimumLevel = LogLevel.Debug, DbContextLoggerOptions? options = null)
Parameters
action
Action<string>Delegate called when there is a message to log.
events
IEnumerable<EventId>The EventId of each event to log.
minimumLevel
LogLevelThe minimum level of logging event to log. Defaults to Debug
options
DbContextLoggerOptions?Formatting options for log messages. Passing null (the default) means use DefaultWithLocalTime
Returns
- DbContextOptionsBuilder
The same builder instance so that multiple calls can be chained.
Remarks
Use the LogTo(Action<string>, LogLevel, DbContextLoggerOptions?) overload for default logging of all events. Use the LogTo(Action<string>, IEnumerable<string>, LogLevel, DbContextLoggerOptions?) overload to log only events in specific categories. Use the LogTo(Action<string>, Func<EventId, LogLevel, bool>, DbContextLoggerOptions?) overload to use a custom filter for events. Use the LogTo(Func<EventId, LogLevel, bool>, Action<EventData>) overload to log to a fully custom logger.
See Using DbContextOptions and Logging for more information and examples.
LogTo(Action<string>, IEnumerable<string>, LogLevel, DbContextLoggerOptions?)
Logs all events in the specified categories using the supplied action. For example, use
optionsBuilder.LogTo(Console.WriteLine, new[] { DbLoggerCategory.Infrastructure.Name })
to log all
events in the DbLoggerCategory.Infrastructure category.
public virtual DbContextOptionsBuilder LogTo(Action<string> action, IEnumerable<string> categories, LogLevel minimumLevel = LogLevel.Debug, DbContextLoggerOptions? options = null)
Parameters
action
Action<string>Delegate called when there is a message to log.
categories
IEnumerable<string>The DbLoggerCategory of each event to log.
minimumLevel
LogLevelThe minimum level of logging event to log. Defaults to Debug
options
DbContextLoggerOptions?Formatting options for log messages. Passing null (the default) means use DefaultWithLocalTime
Returns
- DbContextOptionsBuilder
The same builder instance so that multiple calls can be chained.
Remarks
Use the LogTo(Action<string>, LogLevel, DbContextLoggerOptions?) overload for default logging of all events. Use the LogTo(Action<string>, IEnumerable<EventId>, LogLevel, DbContextLoggerOptions?) overload to log only specific events. Use the LogTo(Action<string>, Func<EventId, LogLevel, bool>, DbContextLoggerOptions?) overload to use a custom filter for events. Use the LogTo(Func<EventId, LogLevel, bool>, Action<EventData>) overload to log to a fully custom logger.
See Using DbContextOptions and Logging for more information and examples.
LogTo(Action<string>, Func<EventId, LogLevel, bool>, DbContextLoggerOptions?)
Logs events filtered by a supplied custom filter delegate. The filter should return true to log a message, or false to filter it out of the log.
public virtual DbContextOptionsBuilder LogTo(Action<string> action, Func<EventId, LogLevel, bool> filter, DbContextLoggerOptions? options = null)
Parameters
action
Action<string>Delegate called when there is a message to log.
filter
Func<EventId, LogLevel, bool>Delegate that returns true to log the message or false to ignore it.
options
DbContextLoggerOptions?Formatting options for log messages. Passing null (the default) means use DefaultWithLocalTime
Returns
- DbContextOptionsBuilder
The same builder instance so that multiple calls can be chained.
Remarks
Use the LogTo(Action<string>, LogLevel, DbContextLoggerOptions?) overload for default logging of all events. Use the LogTo(Action<string>, IEnumerable<EventId>, LogLevel, DbContextLoggerOptions?) Use the LogTo(Action<string>, IEnumerable<string>, LogLevel, DbContextLoggerOptions?) overload to log only events in specific categories. Use the LogTo(Func<EventId, LogLevel, bool>, Action<EventData>) overload to log to a fully custom logger.
See Using DbContextOptions and Logging for more information and examples.
LogTo(Func<EventId, LogLevel, bool>, Action<EventData>)
Logs events to a custom logger delegate filtered by a custom filter delegate. The filter should return true to log a message, or false to filter it out of the log.
public virtual DbContextOptionsBuilder LogTo(Func<EventId, LogLevel, bool> filter, Action<EventData> logger)
Parameters
filter
Func<EventId, LogLevel, bool>Delegate that returns true to log the message or false to ignore it.
logger
Action<EventData>Delegate called when there is a message to log.
Returns
- DbContextOptionsBuilder
The same builder instance so that multiple calls can be chained.
Remarks
Use the LogTo(Action<string>, LogLevel, DbContextLoggerOptions?) overload for default logging of all events. Use the LogTo(Action<string>, IEnumerable<EventId>, LogLevel, DbContextLoggerOptions?) Use the LogTo(Action<string>, IEnumerable<string>, LogLevel, DbContextLoggerOptions?) overload to log only events in specific categories. Use the LogTo(Action<string>, Func<EventId, LogLevel, bool>, DbContextLoggerOptions?) overload to use a custom filter for events.
See Using DbContextOptions and Logging for more information and examples.
ReplaceService<TService, TImplementation>()
Replaces all internal Entity Framework implementations of a service contract with a different implementation.
public virtual DbContextOptionsBuilder ReplaceService<TService, TImplementation>() where TImplementation : TService
Returns
- DbContextOptionsBuilder
The same builder instance so that multiple calls can be chained.
Type Parameters
TService
The type (usually an interface) that defines the contract of the service to replace.
TImplementation
The new implementation type for the service.
Remarks
This method can only be used when EF is building and managing its internal service provider. If the service provider is being built externally and passed to UseInternalServiceProvider(IServiceProvider?), then replacement services should be configured on that service provider before it is passed to EF.
The replacement service gets the same scope as the EF service that it is replacing.
See Using DbContextOptions for more information and examples.
ReplaceService<TService, TCurrentImplementation, TNewImplementation>()
Replaces the internal Entity Framework implementation of a specific implementation of a service contract with a different implementation.
public virtual DbContextOptionsBuilder ReplaceService<TService, TCurrentImplementation, TNewImplementation>() where TCurrentImplementation : TService where TNewImplementation : TService
Returns
- DbContextOptionsBuilder
The same builder instance so that multiple calls can be chained.
Type Parameters
TService
The type (usually an interface) that defines the contract of the service to replace.
TCurrentImplementation
The current implementation type for the service.
TNewImplementation
The new implementation type for the service.
Remarks
This method is useful for replacing a single instance of services that can be legitimately registered multiple times in the EF internal service provider.
This method can only be used when EF is building and managing its internal service provider. If the service provider is being built externally and passed to UseInternalServiceProvider(IServiceProvider?), then replacement services should be configured on that service provider before it is passed to EF.
The replacement service gets the same scope as the EF service that it is replacing.
See Using DbContextOptions for more information and examples.
UseApplicationServiceProvider(IServiceProvider?)
Sets the IServiceProvider from which application services will be obtained. This is done automatically when using 'AddDbContext' or 'AddDbContextPool', so it is rare that this method needs to be called.
public virtual DbContextOptionsBuilder UseApplicationServiceProvider(IServiceProvider? serviceProvider)
Parameters
serviceProvider
IServiceProviderThe service provider to be used.
Returns
- DbContextOptionsBuilder
The same builder instance so that multiple calls can be chained.
Remarks
See Using DbContextOptions for more information and examples.
UseInternalServiceProvider(IServiceProvider?)
Sets the IServiceProvider that the context should resolve all of its services from. EF will create and manage a service provider if none is specified.
public virtual DbContextOptionsBuilder UseInternalServiceProvider(IServiceProvider? serviceProvider)
Parameters
serviceProvider
IServiceProviderThe service provider to be used.
Returns
- DbContextOptionsBuilder
The same builder instance so that multiple calls can be chained.
Remarks
The service provider must contain all the services required by Entity Framework (and the database being used). The Entity Framework services can be registered using an extension method on IServiceCollection. For example, the Microsoft SQL Server provider includes an AddEntityFrameworkSqlServer() method to add the required services.
If the IServiceProvider has a DbContextOptions or DbContextOptions<TContext> registered, then this will be used as the options for this context instance.
See Using DbContextOptions for more information and examples.
UseLoggerFactory(ILoggerFactory?)
Sets the ILoggerFactory that will be used to create ILogger instances for logging done by this context.
public virtual DbContextOptionsBuilder UseLoggerFactory(ILoggerFactory? loggerFactory)
Parameters
loggerFactory
ILoggerFactoryThe logger factory to be used.
Returns
- DbContextOptionsBuilder
The same builder instance so that multiple calls can be chained.
Remarks
There is no need to call this method when using one of the 'AddDbContext' methods, including 'AddDbContextPool'. These methods ensure that the ILoggerFactory used by EF is obtained from the application service provider.
This method cannot be used if the application is setting the internal service provider through a call to UseInternalServiceProvider(IServiceProvider?). In this case, the ILoggerFactory should be configured directly in that service provider.
See Using DbContextOptions and Logging for more information and examples.
UseMemoryCache(IMemoryCache?)
Sets the IMemoryCache to be used for query caching by this context.
public virtual DbContextOptionsBuilder UseMemoryCache(IMemoryCache? memoryCache)
Parameters
memoryCache
IMemoryCacheThe memory cache to be used.
Returns
- DbContextOptionsBuilder
The same builder instance so that multiple calls can be chained.
Remarks
Note that changing the memory cache can cause EF to build a new internal service provider, which may cause issues with performance. Generally it is expected that no more than one or two different instances will be used for a given application.
This method cannot be used if the application is setting the internal service provider through a call to UseInternalServiceProvider(IServiceProvider?). In this case, the IMemoryCache should be configured directly in that service provider.
See Using DbContextOptions and Caching in .NET for more information.
UseModel(IModel)
Sets the model to be used for the context. If the model is set, then OnModelCreating(ModelBuilder) will not be run.
public virtual DbContextOptionsBuilder UseModel(IModel model)
Parameters
model
IModelThe model to be used.
Returns
- DbContextOptionsBuilder
The same builder instance so that multiple calls can be chained.
Remarks
If setting an externally created model FinalizeModel() should be called first.
See Using DbContextOptions and Model Building for more information and examples.
UseQueryTrackingBehavior(QueryTrackingBehavior)
Sets the tracking behavior for LINQ queries run against the context. Disabling change tracking is useful for read-only scenarios because it avoids the overhead of setting up change tracking for each entity instance. You should not disable change tracking if you want to manipulate entity instances and persist those changes to the database using SaveChanges().
public virtual DbContextOptionsBuilder UseQueryTrackingBehavior(QueryTrackingBehavior queryTrackingBehavior)
Parameters
queryTrackingBehavior
QueryTrackingBehavior
Returns
- DbContextOptionsBuilder
The same builder instance so that multiple calls can be chained.
Remarks
This method sets the default behavior for all contexts created with these options, but you can override this behavior for a context instance using QueryTrackingBehavior or on individual queries using the AsNoTracking<TEntity>(IQueryable<TEntity>) and AsTracking<TEntity>(IQueryable<TEntity>) methods.
The default value is TrackAll. This means the change tracker will keep track of changes for all entities that are returned from a LINQ query.
See Using DbContextOptions and Querying data with EF Core for more information and examples.
UseRootApplicationServiceProvider()
Resolves the root IServiceProvider from from the scoped application service provider. The root provider can be used to obtain singleton application services from singleton internal services.
public virtual DbContextOptionsBuilder UseRootApplicationServiceProvider()
Returns
- DbContextOptionsBuilder
The same builder instance so that multiple calls can be chained.
Remarks
This is an advanced option that is rarely needed by normal applications. Calling this method will result in a new internal service provider being created for every different root application service provider.
See Using DbContextOptions for more information and examples.
UseRootApplicationServiceProvider(IServiceProvider?)
Sets the root IServiceProvider from which singleton application services can be obtained from singleton internal services.
public virtual DbContextOptionsBuilder UseRootApplicationServiceProvider(IServiceProvider? rootServiceProvider)
Parameters
rootServiceProvider
IServiceProviderThe service provider to be used.
Returns
- DbContextOptionsBuilder
The same builder instance so that multiple calls can be chained.
Remarks
This is an advanced option that is rarely needed by normal applications. Calling this method will result in a new internal service provider being created for every different root application service provider.
See Using DbContextOptions for more information and examples.