Files
blazor-swm/Features/Utilities/Todo/Cqrs/DeleteTodoByIdHandler.cs
T
2026-07-21 14:35:37 +07:00

36 lines
1008 B
C#

using Indotalent.Infrastructure.Database;
using MediatR;
using Microsoft.EntityFrameworkCore;
namespace Indotalent.Features.Utilities.Todo.Cqrs;
public class DeleteTodoByIdRequest
{
public DeleteTodoByIdRequest(string id) => Id = id;
public string Id { get; set; }
}
public record DeleteTodoByIdCommand(DeleteTodoByIdRequest Data) : IRequest<bool>;
public class DeleteTodoByIdHandler : IRequestHandler<DeleteTodoByIdCommand, bool>
{
private readonly AppDbContext _context;
public DeleteTodoByIdHandler(AppDbContext context) => _context = context;
public async Task<bool> Handle(DeleteTodoByIdCommand request, CancellationToken cancellationToken)
{
var entity = await _context.Todo
.FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);
if (entity == null)
{
return false;
}
_context.Todo.Remove(entity);
await _context.SaveChangesAsync(cancellationToken);
return true;
}
}