feat: add a group command

This commit is contained in:
Polianin Nikita 2024-01-25 17:35:15 +03:00
parent 31c214d955
commit b9b34a29e8
4 changed files with 68 additions and 0 deletions

View File

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

View File

@ -0,0 +1,30 @@
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.Group.Commands.CreateGroup;
public class CreateGroupCommandHandler(IGroupDbContext dbContext) : IRequestHandler<CreateGroupCommand, int>
{
public async Task<int> Handle(CreateGroupCommand request, CancellationToken cancellationToken)
{
var entity = await dbContext.Groups.FirstOrDefaultAsync(g => g.Name == request.Name, cancellationToken: cancellationToken);
if (entity != null)
throw new RecordExistException(typeof(Domain.Schedule.Group), nameof(Domain.Schedule.Group.Name), entity.Id);
var group = new Domain.Schedule.Group()
{
Name = request.Name,
FacultyId = request.FacultyId
};
var result = await dbContext.Groups.AddAsync(group, cancellationToken);
await dbContext.SaveChangesAsync(cancellationToken);
return result.Entity.Id;
}
}

View File

@ -0,0 +1,9 @@
using MediatR;
namespace Mirea.Api.DataAccess.Application.Cqrs.Group.Commands.UpdateGroup;
public class UpdateGroupCommand : IRequest
{
public required int Id { get; set; }
public required int FacultyId { get; set; }
}

View File

@ -0,0 +1,20 @@
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.Group.Commands.UpdateGroup;
public class UpdateGroupCommandHandler(IGroupDbContext dbContext) : IRequestHandler<UpdateGroupCommand>
{
public async Task Handle(UpdateGroupCommand request, CancellationToken cancellationToken)
{
var entity = await dbContext.Groups.FirstOrDefaultAsync(g => g.Id == request.Id, cancellationToken: cancellationToken) ?? throw new NotFoundException(typeof(Domain.Schedule.Group), nameof(Domain.Schedule.Group.Id), request.Id);
entity.FacultyId = request.FacultyId;
await dbContext.SaveChangesAsync(cancellationToken);
}
}