2

我正在使用自动映射器 6.1,我想将一些值从一个对象映射到另一个对象,但有一个条件是这些值不能为空,并且如果我可以轻松使用 ForAllMembers 条件,则不应该映射所有对象属性。我想做的是:

   config.CreateMap<ClassA, ClassB>()
     .ForMember(x => x.Branch, opt => opt.Condition(src => src.Branch != null), 
        cd => cd.MapFrom(map => map.Branch ?? x.Branch))

也试过

 config.CreateMap<ClassA, ClassB>().ForMember(x => x.Branch, cd => {
   cd.Condition(map => map.Branch != null);
   cd.MapFrom(map => map.Branch);
 })

换句话说,对于我在自动映射器配置中定义的每个属性,我想检查它是否为空,以及它是否为来自 x 的空值。

调用此类自动映射器配置如下所示:

 ClassA platform = Mapper.Map<ClassA>(classB);
4

2 回答 2

2

如果我理解正确,它可能比你想象的要简单。opt.Condition不是必需的,因为条件已经在 中得到处理MapFrom

我认为以下内容应该可以实现您想要Branch的:如果不是,它将映射null。如果Branch(来自源)是null,那么它会将目标设置为string.Empty

config.CreateMap<ClassA, Class>()
    .ForMember(x => x.Branch, cd => cd.MapFrom(map => map.Branch ?? string.Empty));

如果您需要使用 x 而不是 的另一个属性string.Empty,那么您可以编写:

config.CreateMap<ClassA, Class>()
    .ForMember(x => x.Branch, cd => cd.MapFrom(map => map.Branch ?? x.AnotherProperty));

如果你想实现复杂的逻辑但保持映射整洁,你可以将你的逻辑提取到一个单独的方法中。例如:

config.CreateMap<ClassA, Class>()
        .ForMember(x => x.Branch, cd => cd.MapFrom(map => MyCustomMapping(map)));

private static string MyCustomMapping(ClassA source)
{
    if (source.Branch == null)
    {
        // Do something
    }
    else
    {
        return source.Branch;
    }
}
于 2017-09-28T11:10:11.607 回答
0

您不需要 MapFrom,但您需要一个 PreCondition。见这里

于 2017-10-01T13:12:33.520 回答