3

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?

sup-team
  • 41
  • 1
  • 7

1 Answers1

3

AutoMapper supports flattening so event this ForMember setup 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 use Include (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 ProjectTo method.

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?)

Guru Stron
  • 102,774
  • 10
  • 95
  • 132