I'm following this tutorial on Microsoft Documentation to create a minimal API and I came across this error on visual studio :
System.InvalidOperationException : 'Failure to infer one or more parameters.
Here the code that I'm using:
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.MapGet("/", () => "Hello world !");
// CREATE NEW ITEM /INVENTORY/ITEM
app.MapPost("/inventory/item", async (Product product, ProductsDb db) =>
{
db.Products.Add(product);
await db.SaveChangesAsync();
return Results.Created($"/inventory/{product.Barcode}", product);
});
// DELETE ITEM /ITEM
app.MapDelete("/item/{bc}", async (int bc, ProductsDb db) =>
{
if (await db.Products.FindAsync(bc) is Product product)
{
db.Products.Remove(product);
await db.SaveChangesAsync();
return Results.Ok(product);
}
return Results.NotFound();
});
// UPDATE ITEM /INVENTORY/item/{barecode}
app.MapPut("/inventory/item/{bc}", async (int bc, Product inputProduct, ProductsDb db)
=>
{
var product = await db.Products.FindAsync(bc);
if (product is null) return Results.NotFound();
product.Name = inputProduct.Name;
product.Category = inputProduct.Category;
product.Price = inputProduct.Price;
product.Discount = inputProduct.Discount;
product.Quantity = inputProduct.Quantity;
await db.SaveChangesAsync();
return Results.NoContent();
});
// GET AL ITEMS /INVENTORY/ITEMS
app.MapGet("/inventory/item", async (ProductsDb db) =>
await db.Products.ToListAsync());
// GET AL ITEMS /INVENTORY/ITEMS/query?category={category}
app.MapGet("/inventory/items/query?category={category}", async (int bc, ProductsDb db)
=>
await db.Products.FindAsync(bc)
is Product product
? Results.Ok(product)
: Results.NotFound());
// GET AL ITEMS SORTED IN DESCENDING /INVENTORY/ITEM/SORT
app.MapGet("/inventory/item/sort", async (ProductsDb db) =>
await db.Products.OrderBy(p =>p.Price).ToListAsync());
app.Run();
class Product
{
public string Name { get; set; }
public string Category { get; set; }
public int Price { get; set; }
public int Discount { get; set; }
public int Quantity { get; set; }
public int Barcode { get; set; }
}
class ProductsDb : DbContext
{
public ProductsDb(DbContextOptions<ProductsDb> options)
: base(options) { }
public DbSet<Product> Products => Set<Product>();
}
What I'm trying to do is to provide some API end point that will get or post some products in a database (Entity framework code first)
I'm using EntityFramework.InMemory like the tutorial but I have no idea why it generates this error, am I doing something wrong ? thank you !