1

Is it possible to map one object to several objects using automapper? I know that it is possible to do it the other way around as shown here.

2
  • 1
    Haven't tried it, but couldn't you just call Map multiple times with the same input, but with different output types? Commented Feb 4, 2016 at 16:29
  • Makes sense. However, I would like write a dedicated mapper. Commented Feb 4, 2016 at 18:04

1 Answer 1

2

One way to do it:

Mapper.CreateMap<MAINSource, MAINDest>()
    .ForMember(dest => dest.Inner1, expression => expression.ResolveUsing(source1 => source1.Inner1))
    .ForMember(dest => dest.Inner2, expression => expression.ResolveUsing(source1 => source1.Inner2));


Mapper.CreateMap<Source1, Dest1>()
    .ForMember(dest => dest.NumValue, expression => expression.ResolveUsing(source1 => source1.NumValue));
Mapper.CreateMap<Source1, Dest2>()
    .ForMember(dest => dest.StringValue, expression => expression.ResolveUsing(source1 => source1.StringValue));

Full example:

public class Source1
{
    public int NumValue { get; set; }
    public string StringValue { get; set; }
}

public class MAINSource
{
    public Source1 Inner1 { get; set; }
    public Source1 Inner2 { get; set; }
}

public class Dest1
{
    public int NumValue { get; set; }
}

public class Dest2
{
    public string StringValue { get; set; }
}

public class MAINDest
{
    public Dest1 Inner1 { get; set; }
    public Dest2 Inner2 { get; set; }
}


Mapper.CreateMap<MAINSource, MAINDest>()
    .ForMember(dest => dest.Inner1, expression => expression.ResolveUsing(source1 => source1.Inner1))
    .ForMember(dest => dest.Inner2, expression => expression.ResolveUsing(source1 => source1.Inner2));


Mapper.CreateMap<Source1, Dest1>()
    .ForMember(dest => dest.NumValue, expression => expression.ResolveUsing(source1 => source1.NumValue));
Mapper.CreateMap<Source1, Dest2>()
    .ForMember(dest => dest.StringValue, expression => expression.ResolveUsing(source1 => source1.StringValue));

var innerSource = new Source1 {NumValue = 1, StringValue = "supervalue"};
var mainSource = new MAINSource
{
    Inner1 = innerSource,
    Inner2 = innerSource
};


var destination = Mapper.Map<MAINSource, MAINDest>(mainSource);

destination.Inner1.NumValue.ShouldEqual(1);
destination.Inner2.StringValue.ShouldEqual("supervalue");
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.