MireaBackend/Application/Cqrs/Campus/Commands/CreateCampus/CreateCampusCommandHandler.cs

31 lines
1.2 KiB
C#
Raw Permalink Normal View History

2024-01-25 17:44:44 +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.Campus.Commands.CreateCampus;
public class CreateCampusCommandHandler(ICampusDbContext dbContext) : IRequestHandler<CreateCampusCommand, int>
{
public async Task<int> Handle(CreateCampusCommand request, CancellationToken cancellationToken)
{
var entity = await dbContext.Campuses.FirstOrDefaultAsync(c => c.CodeName == request.CodeName, cancellationToken: cancellationToken);
if (entity != null)
throw new RecordExistException(typeof(Domain.Schedule.Campus), nameof(Domain.Schedule.Campus.CodeName), entity.Id);
var campus = new Domain.Schedule.Campus()
{
CodeName = request.CodeName,
FullName = request.FullName,
Address = request.Address
};
var result = await dbContext.Campuses.AddAsync(campus, cancellationToken);
await dbContext.SaveChangesAsync(cancellationToken);
return result.Entity.Id;
}
}