'How do I obtain the IConfiguration parameter to instantiate a EF DbContext?
I need to instantiate the following DbContext class:
public NWBContext(DbContextOptions<NWBContext> options, IConfiguration config) : base(options) {
Config = config;
}
My current code to instantiate an instance of NWBContext is below.
string connectionString = connString;
var optionsBuilder = new DbContextOptionsBuilder<NWBContext>();
optionsBuilder.UseSqlServer(connectionString);
var config = new ConfigurationBuilder()
.AddJsonFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"appsettings.json"))
.Build();
using (var dBContext = new NWBContext(optionsBuilder.Options, (IConfiguration)config)) {
}
This is for a class to import data from a CSV file into SQL. The import is too granular for a bulk insert and involves calculations that would be difficult in T-SQL.
The documentation at https://docs.microsoft.com/en-us/ef/core/dbcontext-configuration/#simple-dbcontext-initialization-with-new shows the following example:
var contextOptions = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Test")
.Options;
using var context = new ApplicationDbContext(contextOptions);
The example does not address an IConfiguration parameter.
How would I instantiate the IConfiguration parameter to pass to the NWBContext constructor?
Some documentation implies that IConfiguration could be obtained from services. How would I obtain services?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
