Search code examples
c#asp.net.netautomapper

Mapping complex object in AutoMapper


The following are the simple objects that work fine using AutoMapper:

public class Source
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Destination
{
    public int Id { get; set; }
    public string Name { get; set; }
}

SampleClass.cs

using Automapper;

public class SampleClass
{
    private IMapper _mapper;
    public SampleClass(IMapper mapper)
    {
        _mapper = mapper;
    }

    public void Logic(Souce source)
    {
        var Dest = _mapper.Map<Destination>(source);
    }
}

The above mapping statement works fine and I see all the fields getting mapped from source to destination since it is a simple object.

But my requirement is that: I have a complex object structure as follows :

public class Source
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<SourceChild> lstChild { get; set; }
}

public class SourceChild
{
    public string Address { get; set; }
}

public class Destination
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<SourceDestination> lstChild { get; set; }
}

public class SourceDestination
{
    public string Address { get; set; }
}

public void Logic(Souce source)
{
    var Dest = _mapper.Map<Destination>(source);
}

The above mapping results in an exception saying:

Missing type map configuration or unsupported mapping.

What is it that I am missing here to map the complex object?


Solution

    1. You need to have a mapping profile/configuration as below:
    public class SourceProfile : Profile
    {
        public SourceProfile()
        {
            CreateMap<Source, Destination>();
            CreateMap<SourceChild, SourceDestination>();
        }
    }
    
    1. Register the Mapping profile to Mapper Configuration.
    MapperConfiguration _config = new MapperConfiguration(cfg => cfg.AddProfile<SourceProfile>());
    

    If you are using ASP.NET Core, you register the AutoMapper service into the DI container with the project assembly which contains your Profile class (Assembly Scanning for auto configuration).

    services.AddAutoMapper(/* profileAssembly1 */);