Search code examples
c#-4.0automapperautomapper-5

Keeping source as a copy in destination class using Automapper


Is there a way to keep the entire source object as a copy in my destination class as a property..

e.g.

Source:

class SourceClass
{
    prop string Prop1 { get; set; }
    prop string Prop2 { get; set; }
}

Destination:

class DestinationClass
{
    prop string Prop1 { get; set; }
    prop string Prop2 { get; set; }
    prop SourceClass SourceClassCopy { get; set; }
}

and using automapper configuration something like

AutoMapper.Mapper.Initialize(cfg => {
        cfg.ReplaceMemberName("this", "SourceClassCopy");
        cfg.CreateMap<SourceClass, DestinationClass>(); //or .ForMember("SourceClassCopy", d => d.MapFrom(s => s));
   });

Why I am doing this is coz I am having a hierarchical object and would like to keep a copy for reverse mapping as the Source class doesn't have a default constructor that will help me reverse map. Also the source class is in a library that I can't modify :( and has methods/functions that accept entire source object. Appreciate any help. Thanks.


Solution

  • You can do it this way:

    public class SourceClass
    {
        public string Prop1 { get; set; }
        public string Prop2 { get; set; }
    }
    
    public class DestinationClass
    {
        public string Prop1 { get; set; }
        public string Prop2 { get; set; }
        public SourceClass SourceClassCopy { get; set; }
    }
    
    public class Program
    {
        public void Main()
        {
            var source = new SourceClass();
            source.Prop1 = "Prop1Source";
            source.Prop2 = "Prop2Source";
    
            var destination = new DestinationClass();
            destination.Prop1 = "Prop1Dest";
            destination.Prop2 = "Prop2Dest";
    
            var sourceinDest = new SourceClass();
            sourceinDest.Prop1 = "Prop1sourceinDest";
            sourceinDest.Prop2 = "Prop2sourceinDest";
            destination.SourceClassCopy = sourceinDest;
    
            // Configure AutoMapper
            Mapper.CreateMap<SourceClass, DestinationClass>()
                .ForMember(dest => dest.SourceClassCopy, m=>m.MapFrom(src=>src));
    
            Mapper.Map<SourceClass, DestinationClass>(source, destination);
    
    
            Console.WriteLine(destination.Prop1);
            Console.WriteLine(destination.Prop2);
            Console.WriteLine(destination.SourceClassCopy.Prop1);       
            Console.WriteLine(destination.SourceClassCopy.Prop2);       
        }
    }