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

How to use AutoMapper for mapping with nesting properties?

提问人:user22219327 提问时间:7/13/2023 最后编辑:sup-teamuser22219327 更新时间:7/13/2023 访问量:31

问:

我有 2 个表 [Customer] [Sale] 并且彼此相关,我尝试将 Sale 映射到 SaleDto 并显示客户名称。

客户模型

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }

    public ICollection<Sale>? Sales { get; set; }
}

销售模式

    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; }

销售Dto

    public int Id { get; set; }

    public int CustomerId { get; set; }

    public string CustomerName { get; set; }

    public DateTime? Created { get; set; }

我尝试将 sale.customer.Name 映射到 SaleDto.CustomerName,但它对我不起作用。

自动映射器

    public MappingProfiles()
    {
        CreateMap<Sale, SaleDto>()
            .ForMember(dest => dest.CustomerName,
            opt => opt.MapFrom(src => src.Customer.Name));             
    }

应用程序接口

    [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);
    }

我如何获得带有 NULL 的 customerName,有人可以帮我解决这个问题吗?我尝试显示客户的姓名

响应正文

[
  {
    "id": 1,
    "customerId": 1,
    "customerName": null,
    "amount": 2325,
    "created": "2023-07-10T22:25:49.3510244"
  }
]

有人可以帮我解决这个问题吗?

C# ASP.net-core entity-framework-core 嵌套 自动映射

评论


答:

3赞 Guru Stron 7/13/2023 #1

AutoMapper 支持扁平化,因此实际上不需要此设置。我很确定问题出在存储库中,它没有获取所需的信息。请务必在查询中使用(即)或任何其他形式的加载相关数据ForMemberInclude_context.Customer.Include(c => c.Sales)

此外,我强烈建议研究将 AutoMapper 的可查询扩展与该方法一起使用。ProjectTo

附言

请注意,在实体框架之上使用存储库模式可以被视为反模式,因为 EF 已经是一个存储库(阅读更多 - 存储库模式对实体框架核心有用吗?)