【问题标题】:Automapper Ignore nested propertyAutomapper 忽略嵌套属性
【发布时间】:2020-03-19 21:36:43
【问题描述】:

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

我要做的只是忽略 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 =&gt; x.Category.Created, o =&gt; o.Ignore() 放在.ReverseMap() 之前,我可以将整个对象清空

我应该注意到,类和映射器类当然分布在多个文件中,CategoryMapping 类看起来与 ProductMapping 相同。它正在删除 Created 属性,尽管这是意料之中的。

如果有人可以帮助隔离我的问题,或展示实现此目的的更好方法,我愿意接受建议。在那之前,我将继续尝试解决这个问题。感谢您的帮助!

【问题讨论】:

    标签: c# asp.net-core automapper ef-core-2.0


    【解决方案1】:

    如果我理解正确,如果您想忽略 Category 类中的 Created 字段,那么您应该在从 CategoryDto -> Category 映射时放置忽略逻辑,反之亦然,并且从 ProductDto 映射保持不变。

     CreateMap<Product, ProductDto>()
           .ReverseMap()
    
       CreateMap<Category, CategoryDto>()
           .ReverseMap()
           .ForMember(x => x.Created, o => o.Ignore());
    

    【讨论】:

    • 我试图通过忽略 Created 字段在我的 CategoryMapping 中添加额外的逻辑。但是在查询产品时我仍然得到该属性。我确实必须把它放在 ReverseMap() 方法之后,因为没有 Created 属性的 CategoryD 引发了一个问题(这是有道理的)我不完全确定这个问题是否可能存在于我的 Product 类控制器中,但我感觉 Automapper 就是为解决这个问题而构建的。
    • 我想补充一点,我确实认为这是几个模型的问题。当我查询我的一个模型时,我希望所有嵌套对象都作为它们各自的 DTO 返回
    【解决方案2】:

    可能已经回答了我自己的问题,但我必须将我的 ProductDto 中的数据类型从 Category 切换到 CategoryDto。我假设 Automapper 会自己解决这个问题。

    对不起!也感谢花时间给我答案的人!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-21
      • 1970-01-01
      • 2017-09-22
      • 2017-02-19
      • 2017-12-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多