I have 2 tables [Customer] [Sale] and related with each others, I try to map Sale to SaleDto and show with customer name.
Customer Model
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Sale>? Sales { get; set; }
}
Sale Model
public int Id { get; set; }
public int CustomerId { get; set; }
public DateTime? Created { get; set; }
public Customer? Customer { get; set; }
public ICollection<SaleOrder>? SaleOrders { get; set; }
SaleDto
public int Id { get; set; }
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public DateTime? Created { get; set; }
I try to map the sale.customer.Name to SaleDto.CustomerName, but it didnt work for me.
AutoMapper
public MappingProfiles()
{
CreateMap<Sale, SaleDto>()
.ForMember(dest => dest.CustomerName,
opt => opt.MapFrom(src => src.Customer.Name));
}
API
[HttpGet]
[ProducesResponseType(200, Type = typeof(IEnumerable<Sale>))]
public IActionResult GetSales()
{
var sales = _mapper.Map<List<SaleDto>>(_saleRepository.GetSales());
if (!ModelState.IsValid)
return BadRequest(ModelState);
return Ok(sales);
}
How ever I get the customerName with NULL, can someone help me with this?? I try to show the name of the customer
Response body
[
{
"id": 1,
"customerId": 1,
"customerName": null,
"amount": 2325,
"created": "2023-07-10T22:25:49.3510244"
}
]
Can someone help me with this?