简体   繁体   中英

Automapper: same instance after mapping

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


        }
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM