AutoMapper MapExpression for sub-entity fails

194 views Asked by At

I'm mapping select expression (projection) of Linq query. This is done to decouple logic layer from data access layer and logic layer should use only DTOs.

Expression<Func<CountyInfoDto, CountyInfoDto>> selector = c =>
new CountyInfoDto
{
    Id = c.Id,
    Citizens = c.Citizens.Select(p => new CitizenDto
    {
    }).ToList()
};

var resEx = mapper.MapExpression<Expression<Func<CountyInfo, CountyInfoDto>>>(selector);  

This mapping fails with error Expression of type 'DTOs.CitizenDto' cannot be used for return type 'Entities.Citizen' however in CountyInfoDto property Citizens has type CitizenDto. Please note all mapping profiles are valid and simple objects can be mapped properly.
If I do like this, all works:

Expression<Func<CountyInfoDto, CountyInfoDto>> selector = c =>
new CountyInfoDto
{
    Id = c.Id
};

var resEx = mapper.MapExpression<Expression<Func<CountyInfo, CountyInfoDto>>>(selector);

or this also works:

Expression<Func<CountyInfoDto, CountyInfoDto>> selector = c =>
new CountyInfoDto
{
    Id = c.Id,
    Citizens = new List<CitizenDto>
    {
        new CitizenDto
        {
            Id = c.Citizens.First().Id
        }
    }
};

var resEx = mapper.MapExpression<Expression<Func<CountyInfo, CountyInfoDto>>>(selector);  

is there any possibility to avoid this error?

Classes:

public class CountyInfo
{
    public CountyInfo()
    {
        Citizens = new HashSet<Citizen>();
    }

    public Guid Id { get; set; }

    public string Name { get; set; }

    public ICollection<Citizen> Citizens { get; set; }
}

public class Citizen
{
    public Guid Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string ZipCode { get; set; }
}

public class CountyInfoDto
{
    public CountyInfoDto()
    {
        Citizens = new List<CitizenDto>();
    }

    public Guid Id { get; set; }

    public string Name { get; set; }

    public List<CitizenDto> Citizens { get; set; }
}

public class CitizenDto
{
    public Guid Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string ZipCode { get; set; }
}

Mappings:

CreateMap<CountyInfo, CountyInfoDto>().ReverseMap();
CreateMap<Citizen, CitizenDto>().ReverseMap();

I'm using AutoMapper.Extensions.ExpressionMapping, after update to latest version error is: No coercion operator is defined between types 'Entities.CountyInfo' and 'DTOs.CountyInfoDto'.

0

There are 0 answers