简体   繁体   English

AutoMapper - 从子集合中跳过整个 object

[英]AutoMapper - skip whole object from child collection

I have a parent class that has a list of children objects.我有一个父 class 有一个子对象列表。 Child has a bool property that defines if it should be in the Parent list after mapping. Child 有一个 bool 属性,用于定义映射后它是否应该在 Parent 列表中。 Parent has the same property but it's not the one that's relevant in this case: Parent 具有相同的属性,但在这种情况下它不是相关的:

class Parent
{
   public List<Child> Children { get; set; }
   public bool WillMap { get; set; }
   // more stuff
}
class Child
{
   public bool WillMap { get; set; }
   // more things
}

I was wondering if a mapping can be written that will end up with a Parent with a collection of Child objects that have WillMap == true?我想知道是否可以编写一个映射,它最终会得到一个 Parent 和一组具有 WillMap == true 的 Child 对象? I know about conditional mapping and that we can do something like我知道条件映射,我们可以做类似的事情

CreateMap<Parent, Parent>()
   .ForMember(d => d.Children, opt => opt.Condition(s => s.WillMap == true));

but in this case it's the Parent's WillMap property that's being targeted.但在这种情况下,目标是 Parent 的 WillMap 属性。

Thanks.谢谢。

.ForMember(dest => dest.Children, opt => opt.MapFrom(source => source.Children.Where(child => child.WillMap));

You can perform filtering inside MapFrom您可以在 MapFrom 中执行过滤

.ForMember(d => d.Children, opt => opt.MapFrom((s, d, obje, conext) => s.WillMap && s.Children != null ? conext.Mapper.Map<Child>(s.Children.Where(x => x.WillMap).ToList()) : null));

Or create a custom converter with filtering inside:或者创建一个内部过滤的自定义转换器:

    public class ParentConverter : ITypeConverter<Parent, Parent>
    {
        public Parent Convert(ResolutionContext context)
        {
              // implement conversion logic  


        }
    }

http://docs.automapper.org/en/stable/Custom-type-converters.html http://docs.automapper.org/en/stable/Custom-type-converters.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM