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?
AutoMapper supports flattening so event this
ForMembersetup should not actually be needed. I'm pretty sure that the issue is in the repository which does not fetch needed inrofrmation. Be sure to useInclude(i.e._context.Customer.Include(c => c.Sales)) in the query or any other form of loading related data.Also I highly recommend to look into using the AutoMapper's Queryable Extensions with the
ProjectTomethod.P.S.
Note that using Repository pattern on top of Entity Framework can be considered an antipattern, since EF is already a repository (read more - Is the repository pattern useful with Entity Framework Core?)