如何使用AutoMapper进行嵌套属性映射?

huangapple go评论81阅读模式
英文:

How to use AutoMapper for mapping with nesting properties?

问题

你需要确保在 SaleDto 类型映射中, Customer.Name 的值不为 null。在 AutoMapper 的配置中,请确保 Customer 属性和它的关联也正确地映射了。

英文:

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?

答案1

得分: 3

AutoMapper支持扁平化,因此甚至不需要这个ForMember设置。我相当确信问题出在不获取所需信息的存储库中。确保在查询中使用Include(例如,_context.Customer.Include(c => c.Sales))或任何其他形式的加载相关数据

另外,我强烈建议研究使用AutoMapper的Queryable扩展ProjectTo方法。

P.S.

请注意,在Entity Framework之上使用存储库模式可能被认为是反模式,因为EF已经是一个存储库(详细了解 - 在Entity Framework Core中使用存储库模式有用吗?

英文:

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

huangapple
  • 本文由 发表于 2023年7月13日 13:24:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76676169.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定