AutoMapper映射lambda表达式

时间:2016-05-22 20:36:27

标签: c# lambda automapper

以下是我的情景:

public class Dto {
    public string PrimaryId { get; set; }
    public string SecondaryId { get; set; }
    public DtoType Type { get; set; }
}

public class Record {
    public string PartitionKey { get; set; }
    public string RowKey { get; set; }
    public int Type { get; set; }
}

AutoMapper配置

var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Dto, Record>()
                   .ForMember(dest => dest.RowKey, op => op.MapFrom(src => src.SecondaryId))
                   .ForMember(dest => dest.PartitionKey, op => op.MapFrom(src => $"{src.PrimaryId}.{src.Type}"));
                   .ForMember(dest => dest.Type, op => op.MapFrom(src => src.Type));
                cfg.CreateMap<Record, Dto>()
                   .ForMember(dest => dest.SecondaryId, op => op.MapFrom(src => src.RowKey))
                   .ForMember(dest => dest.PrimaryId, op => op.MapFrom(src => src.PartitionKey.Split('.')[0]))
                   .ForMember(dest => dest.Type, op => op.MapFrom(src => src.Type);
            });
mapper = config.CreateMapper();

Lambda表达式映射

Expression<Func<Dto, bool>> predicate;
var expression = _mapper.Map<Expression<Func<Record, bool>>>(predicate);

我认为我可以通过以下方式查询此方案:

Expression<Func<Dto, bool>> predicate = x => x.PrimaryId == "A" && x.Type == DtoType.SomeType

但上述查询并不起作用。我不完全理解AutoMapper中表达式翻译背后的魔力。

编辑*添加错误消息以获取更多详细信息:

Rewriting child expression from type 'DtoType' to type 'System.Int32' is not allowed, because it would change the meaning of the operation. If this is intentional, override 'VisitUnary' and change it to allow this rewrite.

0 个答案:

没有答案