Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when mapping from Entity to DTO or DTO to Entity using AutoMapper

I'm using EntityFramework as a DataLayer and DTO to transfer data between layer. I develop Windows Forms in N-Tier architecture and when I try to mapping from Entity to DTO in BLL:

public IEnumerable<CategoryDTO> GetCategoriesPaged(int skip, int take, string name)
{
    var categories = unitOfWork.CategoryRepository.GetCategoriesPaged(skip, take, name);
    var categoriesDTO = Mapper.Map<IEnumerable<Category>, List<CategoryDTO>>(categories);

    return categoriesDTO;
}

I've got this error: http://s810.photobucket.com/user/sky3913/media/AutoMapperError.png.html

The error said that I missing type map configuration or unsupported mapping. I have registered mapping using profile in this way at UI Layer:

[STAThread]
static void Main()
{
    AutoMapperBusinessConfiguration.Configure();
    AutoMapperWindowsConfiguration.Configure();
    ...
    Application.Run(new frmMain());
}

and AutoMapper configuration is in BLL:

public class AutoMapperBusinessConfiguration
{
    public static void Configure()
    {
        Mapper.Initialize(cfg =>
        {
            cfg.AddProfile<EntityToDTOProfile>();
            cfg.AddProfile<DTOToEntityProfile>();
        });
    }
}

public class EntityToDTOProfile : Profile
{
    public override string ProfileName
    {
        get { return "EntityToDTOMappings"; }
    }

    protected override void Configure()
    {
        Mapper.CreateMap<Category, CategoryDTO>();
    }
}

public class DTOToEntityProfile : Profile
{
    public override string ProfileName
    {
        get { return "DTOToEntityMappings"; }
    }

    protected override void Configure()
    {
        Mapper.CreateMap<CategoryDTO, Category>();
    }
}

I've got the same error too when mapping from DTO to Entity.

category = Mapper.Map<Category>(categoryDTO);

How to solve this?

like image 337
Willy Avatar asked Jul 20 '14 11:07

Willy


2 Answers

Its because you are using Mapper.Initialize multiple times. If you look at the source code it calls Mapper.Reset() which means only the last mapping defined will work. so instead simply remove the Initialize calls and replace with Mapper.AddProfile< >

like image 99
wal Avatar answered Oct 02 '22 13:10

wal


Use AutoMapper.AssertConfigurationIsValid() after the Configure() calls. If anything fails it will throw an exception with a descriptive text. It should give you more info to debug further.

like image 37
Liviu Mandras Avatar answered Oct 02 '22 13:10

Liviu Mandras