-
Notifications
You must be signed in to change notification settings - Fork 226
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")));- Home
- Compared with the Microsoft scaffolder
- Connection strings
- JetBrains Rider
- Upgrading from v3 to v4
- Saving .tt does nothing
- 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