Home > Software engineering >  Automapper: same instance after mapping
Automapper: same instance after mapping

Time:12-09

I try Automapper and it is very nice but is it possible map two OuterDto source to OuterModel destination with same object InnerDeto like in code? How can I do that dest1.Inner and dest2.Inner after map has same instance? What I know, I think it is not possible. What do you think? Thanks for help me

    public class OuterDto
    {
        public int Value { get; set; }
        public InnerDto Inner { get; set; }

    }

    public class InnerDto
    {
        public int OtherValue { get; set; }
    }

    public class OuterModel
    {
        public int Value { get; set; }
        public InnerModel Inner { get; set; }

    }

    public class InnerModel
    {
        public int OtherValue { get; set; }
    }

    public class test
    {
        public test()
        {
            var config = new MapperConfiguration(cfg => {
                cfg.CreateMap<InnerDto, InnerModel>().ReverseMap();
                cfg.CreateMap<OuterDto, OuterModel>().ReverseMap();
            });
            config.AssertConfigurationIsValid();

            InnerDto innerSource = new InnerDto { OtherValue = 15 };
            var source1 = new OuterDto
            {
                Value = 1,
                Inner = innerSource
            };
            var source2 = new OuterDto
            {
                Value = 2,
                Inner = innerSource
            };
            var mapper = config.CreateMapper();
            source1.Inner.OtherValue = 20;
            var dest1 = mapper.Map<OuterDto, OuterModel>(source1);
            var dest2 = mapper.Map<OuterDto, OuterModel>(source2);
            dest1.Inner.OtherValue = 1000;

            //Result:
            //dest1.Inner.OtherValue = 1000
            //dest2.Inner.OtherValue = 20

            //Expected Result:
            //dest1.Inner.OtherValue = 1000
            //dest2.Inner.OtherValue = 1000


        }
    }

CodePudding user response:

I'm not sure, but try to instanciate OuterModel before calling Map method

            //...
            var mapper = config.CreateMapper();
            source1.Inner.OtherValue = 20;

            var dest1 = new OuterModel();
            mapper.Map(source1, dest1);
            mapper.Map(source2, dest1);
            dest1.Inner.OtherValue = 1000;

NOTE: I haven't tested my code, it's just to give food for thought

CodePudding user response:

Unless you assign dest2 with dest1 which leads to dest2 sharing the same reference as dest1. And AutoMapper does support to perform mapping with the existing instance instead of creating another instance.

var dest2 = dest1; 
mapper.Map<OuterDto, OuterModel>(source2, dest2);

Demo @ .NET Fiddle

  • Related