MireaBackend/Application/Cqrs/Faculty/Commands/CreateFaculty/CreateFacultyCommandHandler.cs
Polianin Nikita 4fe25005af
All checks were successful
.NET Test Pipeline / build-and-test (pull_request) Successful in 1m19s
feat: add a faculty command
2024-01-25 17:39:07 +03:00

30 lines
1.1 KiB
C#

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;
}
}