b0rg
b0rg

Reputation: 1897

Automapper map from inner property to destination class

Cant' seem to figure this one out.

public class DestinationClass
{
    public int InnerPropertyId { get; set; }
    public string StrignValue { get; set; }
}

public class SourceClass
{
    public InnerValue Inner { get; set; }
}

public class InnerValue
{
    public int InnerPropertyId { get; set; }
    public string StrignValue {get;set;}
}

I need to map from SourceClass.InnerValue directly to DestinationClass. How do I do that?

Thanks in advance.

Upvotes: 13

Views: 6721

Answers (4)

mazharenko
mazharenko

Reputation: 635

An alternative approach migth be to make use of the Flattening feature.

Mapper.CreateMap<SourceClass, DestinationClass>()
    .IncludeMembers(s => s.Inner);

Automapper then will use members from InnerValue just like there are in the SourceClass itself

Upvotes: 5

Paul Matovich
Paul Matovich

Reputation: 1516

We did have a problem with the ConvertUsing not giving the fully populated result because our version of SourceClass had an additional value that we wanted to map to the DestinationClass

We did find that the following code gave the desired result:

{
    ...
    Mapper.CreateMap<InnerValue, DestinationClass>(MemberList.Source);
    Mapper.CreateMap<SourceClass, DestinationClass>(MemberList.Source)
          .ConstructUsing(s => Mapper.Map<DestinationClass>(s.Inner))
          .ForSourceMember(m => m.Inner, opt => opt.Ignore());
    ...
}

public class DestinationClass
{
    public int InnerPropertyId { get; set; }
    public string StringValue { get; set; }
    public string SourceClassValue { get; set; }
}

public class SourceClass
{
    public string SourceClassValue { get; set; }
    public InnerValue Inner { get; set; }
}

public class InnerValue
{
    public int InnerPropertyId { get; set; }
    public string StrignValue {get;set;}
}

ConstructUsing continues to map the remaining members after it has mapped the inner members and ConvertUsing does not.

Upvotes: 6

b0rg
b0rg

Reputation: 1897

As usual, right after I hit post question button:

Mapper.Reset();
// from, to
Mapper.CreateMap<InnerValue, DestinationClass>();
Mapper.CreateMap<SourceClass, DestinationClass>()
    .ConvertUsing(s => Mapper.Map<InnerValue, DestinationClass>(s.Inner));

Mapper.AssertConfigurationIsValid();

var source = new SourceClass() { Inner = new InnerValue() { InnerPropertyId = 123, StringValue = "somethinges" } };

var dest = Mapper.Map<SourceClass, DestinationClass>(source);

Upvotes: 13

Dima
Dima

Reputation: 6741

Mapping should looks as follows:

CreateMap<SourceClass, DestinationClass>()
    .ForMember(x => x.InnerPropertyId , x => x.MapFrom(z => z.Inner.InnerPropertyId))
    .ForMember(x => x.StrignValue , x => x.MapFrom(z => z.Inner.StrignValue))
;

Upvotes: 5

Related Questions