自动映射器 - 忽略基于源属性子项的映射

时间:2017-09-26 07:57:06

标签: c# automapper

以下是我的来源类型。在这种情况下,当Ingredients为null或Count()== 0时,如何忽略Pizza元素的映射?

class Menu
{
    public Pizza[] Pizzas { get; set; }
}

class Pizza
{
    public string Name { get; set; }

    public Ingredient[] Ingredients { get; set; }
}

class Ingredient
{
    public int Id { get; set; }

    public string Name { get; set; }
}


CreateMap<Menu, MenuVM>();
CreateMap<Pizza PizzaVM>();
CreateMap<Ingredient, IngredientVM>();

1 个答案:

答案 0 :(得分:0)

如果您想要返回忽略,可以执行以下操作(推荐):

Mapper.CreateMap<Pizza, PizzaVM>()
    .ForMember(dest => dest.Ingredients, opt => opt.Condition(source => string.IsNullOrEmpty(src.Ingredients) || src.Ingredients.Count() == 0))

否则,您可以创建如下所示的ValueResolver,但您需要将true / false结果存储在新字段中:

public class PizzaIngredientResolver : ValueResolver<Pizza, bool>
{
    protected override bool ResolveCore(Pizza src)
    {
        return !string.IsNullOrEmpty(src.Ingredients) && src.Ingredients.Count() != 0;
    }
}

然后,您需要调用MappingConfiguration:

.ForMember(dest => dest.IsIngredientVisible, opts => opts.ResolveUsing<PizzaIngredientResolver>())