如果目标条件为真,则有条件地忽略源中的字段

Conditionally ignore a field from the source if a condition is true on destination

我正在使用 Automapper 从 DTO 更新一系列实体。但是,如果某些条件适用,我不想从 DTO 更新一些属性。例如,实体有一个过去的日期。

使用前提条件选项。这是一个简单的例子:

public class Source
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Dest
{
    public string Name { get; set; }
    public int Age { get; set; }
    public DateTime LastUpdated { get; set; }
}

Name 的映射只有在 LastUpdated 的当前年份是 2015 时才会发生:

Mapper.CreateMap<Source, Dest>()
    .ForMember(d => d.Name, o => o.PreCondition((rc) => ((Dest) rc.DestinationValue).LastUpdated.Year == 2015))
    .ForMember(d => d.LastUpdated, o => o.Ignore());

Mapper.AssertConfigurationIsValid();

在下面的代码中,"dest" 对象将保留名称 "Larry":

var src = new Source {Name = "Bob", Age = 22};
var dest = new Dest {Name = "Larry", LastUpdated = new DateTime(2014, 10, 11)};

Mapper.Map<Source, Dest>(src, dest);

如果您将 LastUpdated 的年份更改为 2015 年,Name 属性 将更新为 "Bob"。