❔ How to bring in DbContext?

app.MapPost("/cities", async ([FromBody] City city) => {
...
});
app.MapPost("/cities", async ([FromBody] City city) => {
...
});
13 Replies
Angius
Angius10mo ago
Inject it Add it as one of the parameters of your lambda
cap5lut
cap5lut10mo ago
in minimal api every service is injected via parameters, this includes ur db context as well. eg, u could also inject an ILogger by adding one as parameter
Timo Martinson
Timo Martinson10mo ago
could someone provide a code snippet ? all i get is:
System.InvalidOperationException: Failure to infer one or more parameters.
Below is the list of parameters that we found:

Parameter | Source
---------------------------------------------------------------------------------
city | Body (Attribute)
dataContext | UNKNOWN
System.InvalidOperationException: Failure to infer one or more parameters.
Below is the list of parameters that we found:

Parameter | Source
---------------------------------------------------------------------------------
city | Body (Attribute)
dataContext | UNKNOWN
Angius
Angius10mo ago
Timo Martinson
Timo Martinson10mo ago
this is my data context:
using GetOut.Models;
using Microsoft.EntityFrameworkCore;

namespace GetOut.Data;

public class DataContext : DbContext
{
public DbSet<City> Cities { get; set; }
public DbSet<Provider> Providers { get; set; }
public DbSet<Event> Events { get; set; }
}
using GetOut.Models;
using Microsoft.EntityFrameworkCore;

namespace GetOut.Data;

public class DataContext : DbContext
{
public DbSet<City> Cities { get; set; }
public DbSet<Provider> Providers { get; set; }
public DbSet<Event> Events { get; set; }
}
do I have to change something?
Angius
Angius10mo ago
No, looks good to me How does your MapPost look with the context injected?
Timo Martinson
Timo Martinson10mo ago
looks like this:
app.MapPost("/cities", async ([FromBody] City city, DataContext dataContext) => {
dataContext.Cities.Add(city);
return Results.Ok();
});
app.MapPost("/cities", async ([FromBody] City city, DataContext dataContext) => {
dataContext.Cities.Add(city);
return Results.Ok();
});
Angius
Angius10mo ago
Try adding [FromServices] attribute to the parameter, then Also, just to make sure, your dbcontext is registered in the services?
Timo Martinson
Timo Martinson10mo ago
System.InvalidOperationException: No service for type 'GetOut.Data.DataContext' has been registered. how to register it ?
Angius
Angius10mo ago
builder.Services.AddDbContext<DataContext>();
Timo Martinson
Timo Martinson10mo ago
OK, I have done it. No database provider has been configured for this DbContext.
Angius
Angius10mo ago
Override the OnConfiguring() method in the dbcontext And configure what provider you want to use
Accord
Accord10mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts