54 lines
1.6 KiB
C#
54 lines
1.6 KiB
C#
using Indotalent.ConfigBackEnd.Exceptions;
|
|
using Indotalent.ConfigBackEnd.Extensions;
|
|
using Indotalent.Infrastructure.Database;
|
|
using MediatR;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace Indotalent.Features.Organization.EmployeeGroup.Cqrs;
|
|
|
|
public class CreateEmployeeGroupRequest
|
|
{
|
|
public string? Name { get; set; }
|
|
public string? Description { get; set; }
|
|
}
|
|
|
|
public class CreateEmployeeGroupResponse
|
|
{
|
|
public string? Id { get; set; }
|
|
public string? Name { get; set; }
|
|
}
|
|
|
|
public record CreateEmployeeGroupCommand(CreateEmployeeGroupRequest Data) : IRequest<CreateEmployeeGroupResponse>;
|
|
|
|
public class CreateEmployeeGroupHandler : IRequestHandler<CreateEmployeeGroupCommand, CreateEmployeeGroupResponse>
|
|
{
|
|
private readonly AppDbContext _context;
|
|
|
|
public CreateEmployeeGroupHandler(AppDbContext context) => _context = context;
|
|
|
|
public async Task<CreateEmployeeGroupResponse> Handle(CreateEmployeeGroupCommand request, CancellationToken cancellationToken)
|
|
{
|
|
var isExists = await _context.EmployeeGroup
|
|
.AnyAsync(x => x.Name == request.Data.Name, cancellationToken);
|
|
|
|
if (isExists)
|
|
{
|
|
throw new AlreadyExistsException("Employee Group", request.Data.Name ?? string.Empty);
|
|
}
|
|
|
|
var entity = new Data.Entities.EmployeeGroup
|
|
{
|
|
Name = request.Data.Name,
|
|
Description = request.Data.Description
|
|
};
|
|
|
|
_context.EmployeeGroup.Add(entity);
|
|
await _context.SaveChangesAsync(cancellationToken);
|
|
|
|
return new CreateEmployeeGroupResponse
|
|
{
|
|
Id = entity.Id,
|
|
Name = entity.Name
|
|
};
|
|
}
|
|
} |