C#C
C#2y ago
Draggo

Put and Delete Methods not working.

Program.cs:
using InventoryPro.Database;
using Microsoft.EntityFrameworkCore;



var builder = WebApplication.CreateBuilder(args);


builder.Services.AddDbContext<InventoryDbContext>(options =>
options.UseInMemoryDatabase("InventoryDatabase"));

var app = builder.Build();
app.Urls.Add("http://localhost:5555");

app.UseHttpsRedirection();
http:
@WebApiHost = http://localhost:5555

GET {{WebApiHost}}/

###

GET {{WebApiHost}}/items

###

POST {{WebApiHost}}/items
Content-Type: application/json

{
"Name" : "Example item 3",
"Description": "Description 3",
"Price": 25.50,
"Quantity": 30
}

###
GET {{WebApiHost}}/items/1

###

PUT {{WebApiHost}}/items
Content-Type: application/json

{
"itemId" : 1,
"Name" : "Example item 1",
"Description": "Description 1",
"Price": 25.50,
"Quantity": 30
}

###

DELETE {{WebApiHost}}/items/1


using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<InventoryDbContext>();
if (!dbContext.Items.Any())
{
dbContext.Items.AddRange(
new Item { Name = "Example Item 1", Description = "Description 1", Price = 10, Quantity = 100 },
new Item { Name = "Example Item 2", Description = "Description 2", Price = 20, Quantity = 50 }
);
dbContext.SaveChanges();
}
}
app.MapGet("/items", async (InventoryDbContext dbContext) =>
await dbContext.Items.ToListAsync());


//app.MapGet("/items/{id}", async (int id, InventoryDbContext dbContext) =>
// await dbContext.Items.FindAsync(id) ?? Results.NotFound());


app.MapPost("/items", async (Item newItem, InventoryDbContext dbContext) =>
{
dbContext.Items.Add(newItem);
await dbContext.SaveChangesAsync();
return Results.Created($"/items/{newItem.ItemId}", newItem);
});


app.MapPut("/items/{itemId}", async (int itemId, Item updatedItem, InventoryDbContext dbContext) =>
{
var item = await dbContext.Items.FindAsync(itemId);
if (item == null) return Results.NotFound();

item.Name = updatedItem.Name;
item.Description = updatedItem.Description;
item.Price = updatedItem.Price;
item.Quantity = updatedItem.Quantity;
await dbContext.SaveChangesAsync();
return Results.NoContent();
});

app.MapDelete("/items/{id}", async (int id, InventoryDbContext dbContext) =>
{
var item = await dbContext.Items.FindAsync(id);
if (item == null) return Results.NotFound();

dbContext.Items.Remove(item);
await dbContext.SaveChangesAsync();
return Results.NoContent();
});

app.Run();
image.png
Was this page helpful?