-
Notifications
You must be signed in to change notification settings - Fork 224
Settings.OnConfiguration
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")));or by manually choosing a connection string with:
var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
optionsBuilder.UseSqlServer("Data Source=(local);Initial Catalog=Northwind;Integrated Security=True");
var db = new MyDbContext(optionsBuilder.Options);or by passing in an IConfiguration via a constructor of the dbcontext:
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:
This is the default. 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");
}
}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 setup your connection using:
services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyDbContext")));