forked from sanchezvem/PyroFetes
MAJ Mathilde
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
using FastEndpoints;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PyroFetes.Models;
|
||||
|
||||
namespace PyroFetes.Endpoints.Product;
|
||||
|
||||
@@ -8,29 +9,50 @@ public class DeleteProductRequest
|
||||
public int Id { get; set; }
|
||||
}
|
||||
|
||||
public class DeleteProductEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<DeleteProductRequest>
|
||||
public class DeleteProductEndpoint(PyroFetesDbContext db) : Endpoint<DeleteProductRequest>
|
||||
{
|
||||
public override void Configure()
|
||||
{
|
||||
Delete("/api/products/{@id}", x => new { x.Id });
|
||||
AllowAnonymous();
|
||||
}
|
||||
|
||||
|
||||
public override async Task HandleAsync(DeleteProductRequest req, CancellationToken ct)
|
||||
{
|
||||
Models.Product? productToDelete = await pyrofetesdbcontext
|
||||
.Products
|
||||
.SingleOrDefaultAsync(p => p.Id == req.Id, cancellationToken: ct);
|
||||
// Récupérer le produit
|
||||
var productToDelete = await db.Products
|
||||
.SingleOrDefaultAsync(p => p.Id == req.Id, ct);
|
||||
|
||||
if (productToDelete == null)
|
||||
if (productToDelete is null)
|
||||
{
|
||||
Console.WriteLine($"Aucun produit avec l'ID {req.Id} trouvé.");
|
||||
await Send.NotFoundAsync(ct);
|
||||
return;
|
||||
}
|
||||
|
||||
pyrofetesdbcontext.Products.Remove(productToDelete);
|
||||
await pyrofetesdbcontext.SaveChangesAsync(ct);
|
||||
// Supprimer les liaisons Price
|
||||
var relatedPrices = await db.Prices
|
||||
.Where(p => p.ProductId == req.Id)
|
||||
.ToListAsync(ct);
|
||||
if (relatedPrices.Any())
|
||||
{
|
||||
db.Prices.RemoveRange(relatedPrices);
|
||||
}
|
||||
|
||||
// Supprimer les liaisons WarehouseProduct
|
||||
var relatedWarehouseProducts = await db.WarehouseProducts
|
||||
.Where(wp => wp.ProductId == req.Id)
|
||||
.ToListAsync(ct);
|
||||
if (relatedWarehouseProducts.Any())
|
||||
{
|
||||
db.WarehouseProducts.RemoveRange(relatedWarehouseProducts);
|
||||
}
|
||||
|
||||
// Supprimer le produit
|
||||
db.Products.Remove(productToDelete);
|
||||
|
||||
await db.SaveChangesAsync(ct);
|
||||
Console.WriteLine($"Produit {req.Id}, ses prix et ses entrepôts liés ont été supprimés avec succès.");
|
||||
|
||||
await Send.NoContentAsync(ct);
|
||||
}
|
||||
|
Reference in New Issue
Block a user