feat: add a campus command

This commit is contained in:
Polianin Nikita 2024-01-25 17:44:44 +03:00
parent 4fe25005af
commit 6fde0003e0
4 changed files with 74 additions and 0 deletions

View File

@ -0,0 +1,10 @@
using MediatR;
namespace Mirea.Api.DataAccess.Application.Cqrs.Campus.Commands.CreateCampus;
public class CreateCampusCommand : IRequest<int>
{
public required string CodeName { get; set; }
public string? FullName { get; set; }
public string? Address { get; set; }
}

View File

@ -0,0 +1,31 @@
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;
}
}

View File

@ -0,0 +1,10 @@
using MediatR;
namespace Mirea.Api.DataAccess.Application.Cqrs.Campus.Commands.UpdateCampus;
public class UpdateCampusCommand : IRequest
{
public required int Id { get; set; }
public string? FullName { get; set; }
public string? Address { get; set; }
}

View File

@ -0,0 +1,23 @@
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.UpdateCampus;
public class UpdateCampusCommandHandler(ICampusDbContext dbContext) : IRequestHandler<UpdateCampusCommand>
{
public async Task Handle(UpdateCampusCommand request, CancellationToken cancellationToken)
{
var entity = await dbContext.Campuses.FirstOrDefaultAsync(c => c.Id == request.Id, cancellationToken: cancellationToken) ?? throw new NotFoundException(typeof(Domain.Schedule.Campus), nameof(Domain.Schedule.Campus.Id), request.Id);
if (!string.IsNullOrEmpty(request.FullName))
entity.FullName = request.FullName;
if (!string.IsNullOrEmpty(request.Address))
entity.Address = request.Address;
await dbContext.SaveChangesAsync(cancellationToken);
}
}