fluentsprings / ExpressMapper

Mapping .Net types
http://www.expressmapper.org
Other
310 stars 65 forks source link

Mapping to Nested Objects #86

Closed leomeuk closed 8 years ago

leomeuk commented 8 years ago

Consider some class with some nested objects,

public class ViewModel
{
    public Range A { get; set; }
    public Range B { get; set; }

    public ViewModel()
    {
        A = new Range();
        B = new Range();
    }
}

where Range is defined as follows,

public class Range
{
    public double Start { get; set; }
    public double End { get; set; }
}

Now suppose I want to map that from a simplified DTO class,

public class DTO
{
    public double StartA { get; set; }
    public double EndA { get; set; }
    public double StartB { get; set; }
    public double EndB { get; set; }
}

If I were to register this mapping explicitly as per documentation I get somewhat unexpected results. Going from a fully populated DTO object to an initialised ViewModel object, the second of the Range objects will be copied correctly, the first will not.

Mapper.Register<DTO, ViewModel>()
    .Member(dest => dest.A.Start, src => src.StartA)
    .Member(dest => dest.A.End, src => src.EndA)
    .Member(dest => dest.B.Start, src => src.StartB)
    .Member(dest => dest.B.End, src => src.EndB);

var dto = new DTO() { StartA = 2, StartB = 6, EndA = 4, EndB = 8 };

ViewModel viewModel = new ViewModel();

Mapper.Map<DTO, ViewModel>(dto, viewModel);

Is this behaviour to be expected?

anisimovyuriy commented 8 years ago

Dear @leomeuk ,

Thanks a lot for your valuable input and using Expressmapper! You did great - except Expressmapper doesn't support destination nested mapping. I think no object-mapper supports it. I think the easiest way to implement registration is:

Mapper.Register<DTO, ViewModel>()
    .Member(dest => dest.A, src => new Range{Start = src.StartA, End =src.EndA})
    .Member(dest => dest.B, src => new Range{Start = src.StartB, End =src.EndB});

Please let me know what do you think and if you have any other concerns.

Thanks a lot!
anisimovyuriy commented 8 years ago

I'm closing the issue. If you you have other concerns please reopen it. Thanks!