-
Notifications
You must be signed in to change notification settings - Fork 306
Expand file tree
/
Copy pathUpdateContactCommand.cs
More file actions
74 lines (65 loc) · 2.62 KB
/
UpdateContactCommand.cs
File metadata and controls
74 lines (65 loc) · 2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//------------------------------------------------------------------------------
// <auto-generated>
// CleanArchitecture.Blazor - MIT Licensed.
// Author: neozhu
// Created/Modified: 2025-03-19
// UpdateContactCommand & handler: updates an existing Contact with cache invalidation and raises ContactUpdatedEvent.
// Docs: https://docs.cleanarchitectureblazor.com/features/contact
// </auto-generated>
//------------------------------------------------------------------------------
//
// Usage:
// Use UpdateContactCommand to update an existing contact. If found, changes are applied, cache is invalidated, and ContactUpdatedEvent is raised.
using CleanArchitecture.Blazor.Application.Features.Contacts.DTOs;
using CleanArchitecture.Blazor.Application.Features.Contacts.Caching;
namespace CleanArchitecture.Blazor.Application.Features.Contacts.Commands.Update;
public class UpdateContactCommand: ICacheInvalidatorRequest<Result<int>>
{
[Description("Id")]
public int Id { get; set; }
[Description("Name")]
public string Name {get;set;}
[Description("Description")]
public string? Description {get;set;}
[Description("Email")]
public string? Email {get;set;}
[Description("Phone number")]
public string? PhoneNumber {get;set;}
[Description("Country")]
public string? Country {get;set;}
public string CacheKey => ContactCacheKey.GetAllCacheKey;
public IEnumerable<string>? Tags => ContactCacheKey.Tags;
private class Mapping : Profile
{
public Mapping()
{
CreateMap<UpdateContactCommand, Contact>(MemberList.None);
CreateMap<ContactDto,UpdateContactCommand>(MemberList.None);
}
}
}
public class UpdateContactCommandHandler : IRequestHandler<UpdateContactCommand, Result<int>>
{
private readonly IApplicationDbContext _context;
private readonly IMapper _mapper;
public UpdateContactCommandHandler(
IMapper mapper,
IApplicationDbContext context)
{
_context = context;
_mapper = mapper;
}
public async Task<Result<int>> Handle(UpdateContactCommand request, CancellationToken cancellationToken)
{
var item = await _context.Contacts.FindAsync(request.Id, cancellationToken);
if (item == null)
{
return await Result<int>.FailureAsync($"Contact with id: [{request.Id}] not found.");
}
item = _mapper.Map(request, item);
// raise a update domain event
item.AddDomainEvent(new ContactUpdatedEvent(item));
await _context.SaveChangesAsync(cancellationToken);
return await Result<int>.SuccessAsync(item.Id);
}
}