Add validation to prevent updates with duplicate national codes
This commit is contained in:
@@ -1,5 +1,7 @@
|
|||||||
using CMSMicroservice.Domain.Events;
|
using CMSMicroservice.Domain.Events;
|
||||||
|
|
||||||
namespace CMSMicroservice.Application.UserCQ.Commands.UpdateUser;
|
namespace CMSMicroservice.Application.UserCQ.Commands.UpdateUser;
|
||||||
|
|
||||||
public class UpdateUserCommandHandler : IRequestHandler<UpdateUserCommand, Unit>
|
public class UpdateUserCommandHandler : IRequestHandler<UpdateUserCommand, Unit>
|
||||||
{
|
{
|
||||||
private readonly IApplicationDbContext _context;
|
private readonly IApplicationDbContext _context;
|
||||||
@@ -11,16 +13,19 @@ public class UpdateUserCommandHandler : IRequestHandler<UpdateUserCommand, Unit>
|
|||||||
|
|
||||||
public async Task<Unit> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
|
public async Task<Unit> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var entity = await _context.Users
|
if (!string.IsNullOrWhiteSpace(request.NationalCode) &&
|
||||||
.FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken) ?? throw new NotFoundException(nameof(User), request.Id);
|
_context.Users.Any(a => a.NationalCode == request.NationalCode))
|
||||||
if (!string.IsNullOrWhiteSpace(request.NationalCode) && entity.NationalCode == request.NationalCode)
|
|
||||||
{
|
{
|
||||||
throw new Exception("کد ملی تکراری است");
|
throw new Exception("کد ملی تکراری است");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var entity = await _context.Users
|
||||||
|
.FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken) ??
|
||||||
|
throw new NotFoundException(nameof(User), request.Id);
|
||||||
request.Adapt(entity);
|
request.Adapt(entity);
|
||||||
_context.Users.Update(entity);
|
_context.Users.Update(entity);
|
||||||
entity.AddDomainEvent(new UpdateUserEvent(entity));
|
entity.AddDomainEvent(new UpdateUserEvent(entity));
|
||||||
await _context.SaveChangesAsync(cancellationToken);
|
await _context.SaveChangesAsync(cancellationToken);
|
||||||
return Unit.Value;
|
return Unit.Value;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user