简体   繁体   中英

How to map one list to two lists using AutoMapper?

If I have the following classes:

public MainModel
{
    public List<ChildModel> Children {get; set;}
}

public ChildModel
{
    public bool IsDifferent {get; set;}
}

public MainDto
{
    public List<ChildDto> Children {get; set;}
    public List<DifferentChildDto> Different {get; set;}
}

public ChildDto
{ }

public DifferentChildDto
{ }

Using AutoMapper , is it possible to split and map the ChildModel list into 2 separate lists based on the property?

The end result shoud be that items with IsDifferent property set will be in the Different list whilst the remaining items are in the Children list.

The mapping should also work in reverse, ie. Merge the two DTO lists into the 1 model list.

Mapper.CreateMap<MainModel, MainDto>()
    .ForMember(d => d.Children, o => o.MapFrom(s => s.Children.Where(c => !c.IsDifferent)))
    .ForMember(d => d.Different, o => o.MapFrom(s => s.Children.Where(c => c.IsDifferent)));

Mapper.CreateMap<ChildModel, ChildDto>();

Mapper.CreateMap<ChildModel, DifferentChildDto>();

Reversing this is not as trivial, you might be better off posting that as a separate question

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.

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