-
Notifications
You must be signed in to change notification settings - Fork 306
Expand file tree
/
Copy pathCreateContactCommand.cs
More file actions
67 lines (59 loc) · 2.35 KB
/
CreateContactCommand.cs
File metadata and controls
67 lines (59 loc) · 2.35 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
//------------------------------------------------------------------------------
// <auto-generated>
// CleanArchitecture.Blazor - MIT Licensed.
// Author: neozhu
// Created/Modified: 2025-03-19
// Command and handler for creating a new Contact.
// Uses caching invalidation and domain events for data consistency.
// Docs: https://docs.cleanarchitectureblazor.com/features/contact
// </auto-generated>
//------------------------------------------------------------------------------
// Usage:
// Use this command to create a new contact with required fields and automatic domain event handling.
using CleanArchitecture.Blazor.Application.Features.Contacts.Caching;
namespace CleanArchitecture.Blazor.Application.Features.Contacts.Commands.Create;
public class CreateContactCommand: 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<CreateContactCommand, Contact>(MemberList.None);
}
}
}
public class CreateContactCommandHandler : IRequestHandler<CreateContactCommand, Result<int>>
{
private readonly IMapper _mapper;
private readonly IApplicationDbContext _context;
public CreateContactCommandHandler(
IMapper mapper,
IApplicationDbContext context)
{
_mapper = mapper;
_context = context;
}
public async Task<Result<int>> Handle(CreateContactCommand request, CancellationToken cancellationToken)
{
var item = _mapper.Map<Contact>(request);
// raise a create domain event
item.AddDomainEvent(new ContactCreatedEvent(item));
_context.Contacts.Add(item);
await _context.SaveChangesAsync(cancellationToken);
return await Result<int>.SuccessAsync(item.Id);
}
}