MireaBackend/Application/Cqrs/Day/Commands/CreateDay/CreateDayCommandHandler.cs

38 lines
1.3 KiB
C#
Raw Normal View History

2024-01-25 17:53:22 +03:00
using MediatR;
using Microsoft.EntityFrameworkCore;
using Mirea.Api.DataAccess.Application.Common.Exceptions;
using Mirea.Api.DataAccess.Application.Interfaces.DbContexts.Schedule;
using System.Threading;
using System.Threading.Tasks;
namespace Mirea.Api.DataAccess.Application.Cqrs.Day.Commands.CreateDay;
public class CreateDayCommandHandler(IDayDbContext dbContext) : IRequestHandler<CreateDayCommand, int>
{
public async Task<int> Handle(CreateDayCommand request, CancellationToken cancellationToken)
{
var entity = await dbContext.Days
.FirstOrDefaultAsync(d =>
d.LessonId == request.LessonId
&& d.PairNumber == request.PairNumber
&& d.GroupId == request.GroupId
&& d.Index == request.Index,
cancellationToken: cancellationToken);
if (entity != null)
throw new RecordExistException(typeof(Domain.Schedule.Day), entity.Id);
var day = new Domain.Schedule.Day()
{
Index = request.Index,
PairNumber = request.PairNumber,
GroupId = request.GroupId,
LessonId = request.LessonId
};
var result = await dbContext.Days.AddAsync(day, cancellationToken);
await dbContext.SaveChangesAsync(cancellationToken);
return result.Entity.Id;
}
}