I have a parent class that has a list of children objects. Child has a bool property that defines if it should be in the Parent list after mapping. Parent has the same property but it's not the one that's relevant in this case:
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? 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.
Thanks.
.ForMember(dest => dest.Children, opt => opt.MapFrom(source => source.Children.Where(child => child.WillMap));
You can perform filtering inside 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.