使用AutoMapper.Extensions.Expression
的表达式映射未映射表达式。
这是我的模特:
public class UserDto
{
public int Id { get; set; }
public User User { get; set; }
//other info
}
public class User
{
public string Email { get; set; }
//other info
}
public class UserEntity
{
public int Id { get; set; }
public string Email { get; set; }
//other info
}
我的映射器:
public static class MapperConfiguration
{
public static void Configure()
{
Mapper.Initialize(cfg =>
{
cfg.AddProfile(new UserDtoProfile());
});
}
}
internal class UserDtoProfile : Profile
{
public UserDtoProfile()
{
CreateMap<UserDto, UserEntity>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.Email, opt => opt.MapFrom(src => src.User.Email));
CreateMap<UserEntity, UserDto>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.User, opt => opt.MapFrom(src => Mapper.Map<UserEntity>(src)));
CreateMap<UserEntity, User>()
.ForMember(dest => dest.Email, opt => opt.MapFrom(src => src.Email)).ReverseMap();
}
}
添加摘要以重现该问题:
static void Main(string[] args)
{
MapperConfiguration.Configure();
var email = "test@test.com";
Expression<Func<UserDto, bool>> filterExpression = x => x.User.Email == email;
var expression = Mapper.Map<Expression<Func<UserEntity, bool>>>(filterExpression);
Console.WriteLine("Old Expression : " + filterExpression.Body);
Console.WriteLine("New Expression : " + expression.Body);
Console.Read();
}
此输出为:
旧表达式:(x.User.Email ==“ asd”)
新表达式:(x.User.Email ==“ asd”)
但是,我希望它能输出:
旧表达式:(x.User.Email ==“ asd”)
新表达式:(x.Email ==“ asd”)
无法正常运行的特定行是:
Expression<Func<UserDto, bool>> filterExpression = x => x.User.Email == email;
var expression = Mapper.Map<Expression<Func<UserEntity, bool>>>(filterExpression);
我正在使用AutoMapper
v8.0.0和AutoMapper.Extensions.Expression
v2.0.0
答案 0 :(得分:1)
您忘记配置表达式映射。您的设置应为:
Mapper.Initialize(cfg =>
{
cfg.AddExpressionMapping();
cfg.AddProfile(new UserDtoProfile());
});
我还没有真正使用过AutoMapper,也从未使用过表达式映射,但是根据this github issue,对于表达式来说,映射似乎是向后的。您当前的映射将不起作用,并且在执行时会崩溃。您需要将映射更改为:
internal class UserDtoProfile : Profile
{
public UserDtoProfile()
{
CreateMap<UserDto, UserEntity>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.Email, opt => opt.MapFrom(src => src.User.Email))
.ReverseMap();
CreateMap<UserEntity, User>()
.ForMember(dest => dest.Email, opt => opt.MapFrom(src => src.Email)).ReverseMap();
}
}
运行此命令可获得输出:
旧表达式:(x.User.Email ==“ asd”)
新表达式:(x.Email ==“ asd”)