0

我正在映射 Linq 查询的选择表达式(投影)。这样做是为了将逻辑层与数据访问层分离,并且逻辑层应该只使用 DTO。

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);  

此映射因错误而失败,Expression of type 'DTOs.CitizenDto' cannot be used for return type 'Entities.Citizen'但在CountyInfoDto属性Citizens中具有 type CitizenDto。请注意所有映射配置文件都是有效的,并且可以正确映射简单的对象。
如果我这样做,一切正常:

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

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

或者这也有效:

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);  

有没有可能避免这个错误?

课程:

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; }
}

映射:

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

我正在使用AutoMapper.Extensions.ExpressionMapping,更新到最新版本后错误是:No coercion operator is defined between types 'Entities.CountyInfo' and 'DTOs.CountyInfoDto'.

4

0 回答 0