I'm trying to use this DbContext
in a POST
method to add a record.
The constructor of the controller with this method is as follows:
public CookieController(ILogger<CookieController> logger, ICookieRepository cookieRepository)
{
_logger = logger;
_cookieRepository = cookieRepository;
}
Here is the method:
[HttpPost(Name = "")]
public IEnumerable<Cookie> PostCookie([FromBody] Cookie data)
{
DbContextOptions<ReactWithASPDbContext> options = new DbContextOptions<ReactWithASPDbContext>();
ReactWithASPDbContext dbContext = new ReactWithASPDbContext(options);
// ...
}
The DbContext
class looks like this:
public class ReactWithASPDbContext : DbContext
{
public ReactWithASPDbContext(DbContextOptions<ReactWithASPDbContext> options):
base(options)
{
}
// ...
}
This is the Program.cs
code:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<ReactWithASPDbContext>(options => {
options.UseSqlServer(
builder.Configuration["ConnectionStrings:ReactWithASPDbContextConnection"]); });
var app = builder.Build();
DbInitializer.Seed(app);
This is the DbInitializer
method, and it works:
public static void Seed(IApplicationBuilder applicationBuilder)
{
ReactWithASPDbContext context =
applicationBuilder.ApplicationServices
.CreateScope()
.ServiceProvider
.GetRequiredService<ReactWithASPDbContext>();
// ...
}
The appsettings.json
has this content:
"ConnectionStrings": {
"ReactWithASPDbContextConnection": "Server=
(localdb)\mssqllocaldb;Database=ReactWithASP;Trusted_Connection=True;MultipleActiveResultSets=True" }
But the configuration is generating this error:
No database provider has been configured for this DbContext. A provider can be configured by overriding the 'DbContext.OnConfiguring' method or by using 'AddDbContext' on the application service provider. If 'AddDbContext' is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
I'm assuming that I do not need to recreate the init stuff in the Program.cs
file that creates an IApplicationBuilder
etc. There should be a way to pass along the context once its created right?
It tells you that you have not added something like this
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(_connectionString);
}
as in
public class SomeContext: DbContext
{
private readonly string _connectionString;
public SomeContext(string connString) : base()
{
_connectionString= connString;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(_connectionString);
}
// Add DB sets here
}