提问人:Sridhar 提问时间:12/27/2018 最后编辑:user9912639Sridhar 更新时间:12/28/2018 访问量:2064
Automapper 表达式映射问题
Automapper Expression Mapping Issue
问:
表达式映射使用不是映射表达式。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 = "[email protected]";
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);
我正在使用 v8.0.0 和 v2.0.0AutoMapper
AutoMapper.Extensions.Expression
答:
4赞
user9912639
12/28/2018
#1
您忘记配置表达式映射。您的设置应为:
Mapper.Initialize(cfg =>
{
cfg.AddExpressionMapping();
cfg.AddProfile(new UserDtoProfile());
});
我没有真正使用过 AutoMapper,也从未使用过表达式映射,但是根据这个 github 问题,表达式的映射似乎是向后的。您当前的映射将不起作用,并且在执行时会崩溃。您需要将映射更改为:
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”)
评论