Automapper忽略嵌套属性

问题描述 投票:1回答:1

我已经在互联网上搜索了几个小时,似乎无法为自己找到任何解决方案,也无法理解我正在寻找的其他一些类似答案。

我要做的就是忽略AutoMapper中嵌套对象的属性。这是我正在使用的模型的简要概述(出于这个问题的目的,我删除了一些属性以使其变得更小)。

public class Product 
{
  public int ProductId { get; set; }
  public string Name { get; set; }
  public decimal Price { get; set; }
  public int CategoryId { get; set; }

  public Category Category { get; set; }
}

public class ProductDto 
{
  public int ProductId { get; set; }
  public string Name { get; set; }
  public decimal Price { get; set; }
  public int CategoryId { get; set; }

  public Category Category { get; set; }
}

public class Category
{
  public int CategoryId { get; set; }
  public string Name { get; set; }
  public string LabelColor { get; set; }
  public DateTime Created { get; set; }
}

public class CategoryDto
{
  public int CategoryId { get; set; }
  public string Name { get; set; }
  public string LabelColor { get; set; }
}

基本上,我想要的只是在通过API查询产品时,自动映射器会忽略来自Category类的Created属性。我最接近实现此目标的方法是在查询时忽略整个Category对象。

这是我的Product类的当前映射配置

public class ProductMapping: Profile
{
  public ProductMapping()
  {
    CreateMap<Product, ProductDto>()
       .ReverseMap()
       .ForMember(x => x.ProductId, o => o.Ignore());
  }
}

通过将.ForPath(x => x.Category.Created, o => o.Ignore()放在.ReverseMap()之前,我能够使整个对象无效

我应该注意,这些类和映射器类当然是通过多个文件分发的,并且CategoryMapping类看起来与ProductMapping相同。它正在删除Created属性,尽管这是预期的。

[如果有人可以帮助隔离我的问题,或者演示实现此问题的更好方法,我欢迎提出建议。到那时,我将继续尝试解决此问题。感谢您的帮助!

c# asp.net-core automapper ef-core-2.0
1个回答
0
投票

如果我正确理解了是否要忽略Category类中的Created字段,那么当从CategoryD映射到Category时(​​或者反之亦然,从ProductD映射到的映射则保持不变。)

 CreateMap<Product, ProductDto>()
       .ReverseMap()
   CreateMap<Category, CategoryDto>()
       .ReverseMap()
       .ForMember(x => x.Created, o => o.Ignore());
© www.soinside.com 2019 - 2024. All rights reserved.