简体   繁体   中英

Automapper - Map list of objects to single complex type with nested objects

I am using an Automapper and I need to map a list of objects to a single complex type, which has a lot of nested objects, but I can't find what may be the right way to do that. Of course I have a lot more concrete objects, but I'm just simplifying my situation.

Source:

public abstract class SourceBase 
{
    public int? Value { get; set; }
}

public class Source1 : SourceBase
{
}

public class Source2 : SourceBase
{
}

Destination:

public abstract class DestBase 
{
    public int? Value { get; set; }
}

public class Dest1 : DestBase
{
}

public class Dest2 : DestBase
{
}

I have this response from the service:

public List<SourceBase> Foo { get; set; }

And I want to map it into this object:

public class DestObj 
{
    public Dest1 Dest1Obj { get; set; }
    public Dest2 Dest2Obj { get; set; }
}

Thank you!

Basically I've written a custom mapper with Linq.

CreateMap<List<SourceBase>, DestObj>()
    .ForMember(dest => dest.Dest1Obj, opt => opt.MapFrom(src => src.Single(x => x.GetType() == typeof(Source1))))
    .ForMember(dest => dest.Dest2Obj, opt => opt.MapFrom(src => src.Single(x => x.GetType() == typeof(Source2))));

CreateMap<Source1, Dest1>();
CreateMap<Source2, Dest2>();

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