forked from sanchezvem/PyroFetes
51 lines
1.5 KiB
C#
51 lines
1.5 KiB
C#
using FastEndpoints;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using PyroFetes.Models;
|
|
|
|
namespace PyroFetes.Endpoints.Supplier;
|
|
|
|
public class DeleteSupplierRequest
|
|
{
|
|
public int Id { get; set; }
|
|
}
|
|
|
|
public class DeleteSupplierEndpoint(PyroFetesDbContext pyrofetesdbcontext) : Endpoint<DeleteSupplierRequest>
|
|
{
|
|
public override void Configure()
|
|
{
|
|
Delete("/api/suppliers/{@id}", x => new { x.Id });
|
|
AllowAnonymous();
|
|
}
|
|
|
|
public override async Task HandleAsync(DeleteSupplierRequest req, CancellationToken ct)
|
|
{
|
|
var supplierToDelete = await pyrofetesdbcontext
|
|
.Suppliers
|
|
.SingleOrDefaultAsync(s => s.Id == req.Id, ct);
|
|
|
|
if (supplierToDelete is null)
|
|
{
|
|
Console.WriteLine($"Aucun fournisseur avec l'ID {req.Id} trouvé.");
|
|
await Send.NotFoundAsync(ct);
|
|
return;
|
|
}
|
|
|
|
// Supprimer les liaisons Price avant le fournisseur
|
|
var relatedPrices = await pyrofetesdbcontext.Prices
|
|
.Where(p => p.SupplierId == req.Id)
|
|
.ToListAsync(ct);
|
|
|
|
if (relatedPrices.Any())
|
|
{
|
|
pyrofetesdbcontext.Prices.RemoveRange(relatedPrices);
|
|
}
|
|
|
|
// Supprimer le fournisseur
|
|
pyrofetesdbcontext.Suppliers.Remove(supplierToDelete);
|
|
|
|
await pyrofetesdbcontext.SaveChangesAsync(ct);
|
|
Console.WriteLine($"Fournisseur {req.Id} et ses prix liés supprimés avec succès.");
|
|
|
|
await Send.NoContentAsync(ct);
|
|
}
|
|
} |