MireaBackend/Application/Cqrs/Faculty/Commands/CreateFaculty/CreateFacultyCommandHandler.cs

30 lines
1.1 KiB
C#
Raw Permalink Normal View History

2024-01-25 17:39:07 +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.Faculty.Commands.CreateFaculty;
public class CreateFacultyCommandHandler(IFacultyDbContext dbContext) : IRequestHandler<CreateFacultyCommand, int>
{
public async Task<int> Handle(CreateFacultyCommand request, CancellationToken cancellationToken)
{
var entity = await dbContext.Faculties.FirstOrDefaultAsync(f => f.Name == request.Name, cancellationToken: cancellationToken);
if (entity != null)
throw new RecordExistException(typeof(Domain.Schedule.Faculty), nameof(Domain.Schedule.Faculty.Name), entity.Id);
var faculty = new Domain.Schedule.Faculty()
{
Name = request.Name,
CampusId = request.CampusId
};
var result = await dbContext.Faculties.AddAsync(faculty, cancellationToken);
await dbContext.SaveChangesAsync(cancellationToken);
return result.Entity.Id;
}
}