-
Notifications
You must be signed in to change notification settings - Fork 226
Settings.OnConfiguration
Chooses what goes inside the generated DbContext.OnConfiguring() - an embedded connection string, an injected IConfiguration, or nothing at all.
| Type |
OnConfiguration enum: ConnectionString, Configuration, Omit
|
| Default | OnConfiguration.ConnectionString |
| Applies to |
EF Core only. It has no effect on EF 6, which has no OnConfiguring
|
| Databases | All |
In Database.tt? |
Yes |
EF Core needs to be told two things before it can talk to a database: which provider to use, and what
connection string to use. OnConfiguring is the hook where a DbContext can answer that itself, rather than
being handed a configured DbContextOptions from outside.
The three values are three answers to "where does the connection string come from?".
| Value | Where the connection string comes from | Ends up in source control? |
|---|---|---|
ConnectionString |
Hard-coded in the generated file, copied from Settings.ConnectionString
|
Yes |
Configuration |
An IConfiguration injected into the constructor, read at run time |
No |
Omit |
Nowhere - you configure the context when you register it | No |
Note the guard in all generated versions: if (!optionsBuilder.IsConfigured). If something already configured
the context - dependency injection, a test fixture - OnConfiguring stands aside. So even
ConnectionString mode does not stop you overriding it in production.
The connection string from Settings.ConnectionString is written straight into the file.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(@"Data Source=(local);Initial Catalog=DocSamples;Integrated Security=True");
}
}Switching to Configuration changes three things: a using, a field and constructor, and the body of
OnConfiguring. Here is everything that differs from the default:
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.Extensions.Configuration;
using System;
// ...
{
private readonly IConfiguration? _configuration;
public MyDbContext()
// ...
public MyDbContext(IConfiguration configuration)
{
_configuration = configuration;
}
public DbSet<Category> Categories { get; set; } // Category
// ...
{
if (!optionsBuilder.IsConfigured && _configuration != null)
{
optionsBuilder.UseSqlServer(_configuration.GetConnectionString(@"MyDbContext"));
}The key passed to GetConnectionString is Settings.ConnectionStringName, so this needs a matching entry in
appsettings.json:
{
"ConnectionStrings": {
"MyDbContext": "Data Source=(local);Initial Catalog=MyDatabase;Integrated Security=True;Encrypt=false;TrustServerCertificate=true"
}
}The _configuration != null check matters: the parameterless constructor leaves the field null, so a context
created with new MyDbContext() gets no connection string rather than a NullReferenceException.
No OnConfiguring method is generated at all. Compared with the default, exactly this disappears:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(@"Data Source=(local);Initial Catalog=DocSamples;Integrated Security=True");
}
}Nothing replaces it. The context is now entirely dependent on being handed configured options:
builder.Services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("MyDbContext")));
builder.Services.AddScoped<IMyDbContext, MyDbContext>();Omit for anything you deploy. Register the context in Program.cs and configure it there. The
connection string lives in configuration, the provider is chosen in one obvious place, and the generated code
has no opinion about either. This is the standard ASP.NET Core shape.
Omit is required for MySQL. Pomelo's UseMySql() takes a mandatory ServerVersion argument that the
generator does not emit, so ConnectionString and Configuration both produce code that does not compile.
See MySQL.
ConnectionString for a spike, a sample, or a console app where a working new MyDbContext() matters
more than where the string lives. It is the default because it is the one that works with no further setup.
Configuration when you want new MyDbContext(configuration) to work without a DI container - a
migration tool, a background job, an integration test harness.
ConnectionString mode commits your connection string. Database.tt already contains it, so it is
already in source control, but this copies it into the generated .cs as well - and that file is the one
people paste into issues. If it contains a password, use Omit or Configuration. See
Connection strings for keeping it out of the repository altogether.
This is EF Core only. On EF 6 the setting is read and ignored. EF 6 uses
Settings.AddParameterlessConstructorToDbContext and the connection string name instead.
Settings.ConnectionStringActions applies to all three modes except Omit, where there is no call to
append to. Use it for .EnableRetryOnFailure(...) and similar.
Omit plus Settings.AddIDbContextFactory still generates a factory, and that factory calls the
parameterless constructor. With Omit the resulting context has no configuration, so design-time tooling that
uses the factory - dotnet ef migrations - will fail until you configure it yourself.
A small EF Core console application
using Settings.OnConfiguration = OnConfiguration.Configuration;, loading its connection string from
appsettings.{environment}.json at run time.
- Connection strings - the two connection string settings, and how to keep secrets out of the repo
-
Settings.ConnectionStringName - the key
Configurationmode looks up - Settings.ConnectionStringActions
-
MySQL - why
Omitis not optional there - Settings Reference
- Settings A-Z - every setting, with a page each
- Common Settings Types Explained
- Settings Callbacks
- Settings runtime values and helpers
- Filtering
- Full Control Over the Generated Code
- Enum Generation from Table Data
- Owned Entities
- JSON column support
- Global Query Filters
- Extended Property Names Feature
- Partial Properties
- File-Scoped Namespaces
- Data Annotations
- Spatial Types
- HierarchyId
- RowVersion and TimeStamp columns
- Lazy Loading
- Stored proc result sets
- Custom File-Based Templates
- Extra entities via partial classes
- INotifyPropertyChanged
- Syntax colour for T4