feat: add a professor create

This commit is contained in:
Polianin Nikita 2024-01-21 23:13:18 +03:00
parent 9b0e5a3f15
commit 654065f016
2 changed files with 39 additions and 0 deletions

View File

@ -0,0 +1,9 @@
using MediatR;
namespace Mirea.Api.DataAccess.Application.Cqrs.Professor.Commands.CreateProfessor;
public class CreateProfessorCommand : IRequest<int>
{
public required string Name { get; set; }
public string? AltName { get; set; }
}

View File

@ -0,0 +1,30 @@
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Mirea.Api.DataAccess.Application.Common.Exceptions;
using Mirea.Api.DataAccess.Application.Interfaces.DbContexts.Schedule;
namespace Mirea.Api.DataAccess.Application.Cqrs.Professor.Commands.CreateProfessor;
public class CreateProfessorCommandHandler(IProfessorDbContext dbContext) : IRequestHandler<CreateProfessorCommand, int>
{
public async Task<int> Handle(CreateProfessorCommand request, CancellationToken cancellationToken)
{
var entity = await dbContext.Professors.FirstOrDefaultAsync(p => p.Name == request.Name, cancellationToken: cancellationToken);
if (entity != null)
throw new RecordExistException(typeof(Domain.Schedule.Professor), nameof(Domain.Schedule.Professor.Name), entity.Id);
var professor = new Domain.Schedule.Professor()
{
Name = request.Name,
AltName = request.AltName
};
var result = await dbContext.Professors.AddAsync(professor, cancellationToken);
await dbContext.SaveChangesAsync(cancellationToken);
return result.Entity.Id;
}
}