0

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!

2
  • Why though? You get a list of SourceBase? Why not map it to a list of DestBase? Commented Jan 7, 2020 at 9:30
  • Because we want to make it simpler for frontend view models Commented Jan 7, 2020 at 9:47

1 Answer 1

1

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>();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.