[英]Automapper - ignoring mapping based on source property child item
Below are my source types. 以下是我的来源类型。 In this scenario how can I ignore mapping of Pizza element when Ingredients are null or Count() == 0 ?
在这种情况下,当成分为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>();
If you would like to return Ignore you can do the following (recommended): 如果您想返回“忽略”,则可以执行以下操作(建议):
Mapper.CreateMap<Pizza, PizzaVM>()
.ForMember(dest => dest.Ingredients, opt => opt.Condition(source => string.IsNullOrEmpty(src.Ingredients) || src.Ingredients.Count() == 0))
Else you can create a ValueResolver like the following, but you would need to store the true/false result in a new field: 否则,您可以像下面那样创建ValueResolver,但是您需要将true / false结果存储在新字段中:
public class PizzaIngredientResolver : ValueResolver<Pizza, bool>
{
protected override bool ResolveCore(Pizza src)
{
return !string.IsNullOrEmpty(src.Ingredients) && src.Ingredients.Count() != 0;
}
}
You will then need to call in the MappingConfiguration: 然后,您需要调用MappingConfiguration:
.ForMember(dest => dest.IsIngredientVisible, opts => opts.ResolveUsing<PizzaIngredientResolver>())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.