-
Notifications
You must be signed in to change notification settings - Fork 227
Settings.OnConfiguration
public enum OnConfiguration
{
Configuration,
ConnectionString,
Omit
}
Here is a small EFCore7 console application using Settings.OnConfiguration = OnConfiguration.Configuration;
and loading its connection string from appsettings.{environment}.json
during runtime.
This setting has no effect on EF 6. It is only used for EF Core.
Normally the connection string is passed via Startup.ConfigureServices and IMyDbContext is dependency injected into your controllers using:
services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyDbContext")));
...
// Scoped is usually what you need for a database context.
// You get back the same database object within a request.
services.AddScoped<IMyDbContext, MyDbContext>();
or by manually choosing a connection string with:
var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
optionsBuilder.UseSqlServer("Data Source=(local);Initial Catalog=Northwind;Integrated Security=True;Encrypt=false;TrustServerCertificate=true");
var db = new MyDbContext(optionsBuilder.Options);
or by passing in an IConfiguration via a constructor of the DB context:
private readonly IConfiguration _configuration;
public MyDbContext(IConfiguration configuration)
{
_configuration = configuration;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured && _configuration != null)
{
optionsBuilder.UseSqlServer(_configuration.GetConnectionString("MyDbContext"));
}
}
The OnConfiguration
enumeration controls the generation of the DbContext.OnConfiguration()
function in different ways:
The code is generated as:
private readonly IConfiguration _configuration;
public MyDbContext(IConfiguration configuration)
{
_configuration = configuration;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured && _configuration != null)
{
optionsBuilder.UseSqlServer(_configuration.GetConnectionString(@"MyDbContext"));
}
}
The code is generated as:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(@"Data Source=(local);Initial Catalog=Northwind;Integrated Security=True;Encrypt=false;TrustServerCertificate=true");
}
}
The above connection string is taken from your setting of Settings.ConnectionString.
This completely removes the OnConfiguring
function altogether. This assumes IMyDbContext is dependency injected into your controllers/services/classes, and that you have set up your connection using:
services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyDbContext")));
...
// Scoped is usually what you need for a database context.
// You get back the same database object within a request.
services.AddScoped<IMyDbContext, MyDbContext>();