【问题标题】:Avoiding flattening of property "Value" in AutoMapper避免 AutoMapper 中属性“Value”的扁平化
【发布时间】:2017-03-17 12:47:30
【问题描述】:

我们正在使用 AutoMapper 4.1.1(将很快更新到 6,但我们需要一些时间来更改项目)并且遇到了这个问题:在源类中,我们在目标类中有一个属性“int?MyProp”我们有字符串“MyPropValue”,它不应该从 MyProp 映射。但是,当 MyProp 的值不为空时,AutoMapper 会映射它(使用 MyProp.Value,扁平化)。我们可以使用 Ignore() 来忽略映射,但由于我们有许多这样的属性,我们正在寻找一种方法来使用一个配置来完成它,而不会破坏映射的其余部分。

下面是一些示例代码:

class Program
{
    static void Main(string[] args)
    {
        var map = Mapper.CreateMap<Dto, Model>();
        var dto = new Dto() {MyProp = 10};
        var model = Mapper.Map<Dto, Model>(dto);
        Console.WriteLine(model.MyPropValue);   // MyPropValue should be empty but it gets mapped
    }
}

public class Dto
{
    public int? MyProp { get; set; }
}

public class Model
{
    public string MyPropValue { get; set; }
}

【问题讨论】:

  • 我们会将所有属性重命名为 MyPropSomethingElse 而不是 MyPropValue,但看看是否有更好的解决方案会很有趣。

标签: automapper


【解决方案1】:
Mapper.CreateMap<SourceType, DestinationType>()
  .ForAllMembers(opt => opt.Condition(srs => !srs.IsSourceValueNull));

允许您跳过所有空值。
Automapper skip null values with custom resolver

【讨论】:

  • 我对空值没有问题,恰恰相反 - 非空值。
  • 我相信您的解决方案将涉及使用根据您的喜好调整的条件。
猜你喜欢
  • 2016-04-02
  • 2014-08-12
  • 2021-07-16
  • 1970-01-01
  • 1970-01-01
  • 2020-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多