C#C
C#3y ago
Johannes M

✅ AutoMapper - mapping record to a class (.NET 7)

I am using mediatr for my project and I have my command using a sealed record and when I try to map my record to my entity I run into an AutoMapper Extension error.

Error: Exception thrown: 'AutoMapper.AutoMapperMappingException' in AutoMapper.dll

CODE:
public sealed record CreateProductCommand(string Name, string? Description, string Code, decimal Price);

public class Product : BaseAuditableEntity
{
    public required string Name { get; set; }
    public string? Code { get; set; }
    public string? Description { get; set; }
    public decimal Price { get; set; }
}

public async Task<Result> Handle(CreateProductCommand request, CancellationToken cancellationToken)
{
    var product = _mapper.Map<Product>(request);
    product.AddDomainEvent(new CreatedEvent<Product>(product));
    _unitOfWork.Products.Insert(product);
    await _unitOfWork.SaveChangesAsync(cancellationToken);

    return Result.Success();
}


When my CreateProductCommand was still a class the mapping worked with no issues.
Was this page helpful?