关于编码的自动映射成员映射SeemsConvoluted

时间:2015-08-20 02:11:34

标签: c# automapper

我试图找到实现此目的的正确方法。

 return isOptionTrue? Mapper.Map<Context>(myObject) : Mapper.Map<ReplayContext>(myObject);

Context具有我实际需要的所有字段。

public class ContextReplay: Context
{
    //This class is a work around to trick Automapper
}

当然是映射

Mapper.CreateMap<myObject, Context>()
      .ForMember(x => x.Id, opt => opt.MapFrom(y => y.Id))
      .ForMember(x => x.Name, opt => opt.MapFrom(y => y.Name));
      .ForMember(x => x.Important, opt => opt.MapFrom(y => y.NormalProp));


Mapper.CreateMap<myObject, ContextReplay>()
      .ForMember(x => x.WellId, opt => opt.MapFrom(y => y.Id))
      .ForMember(x => x.Name, opt => opt.MapFrom(y => y.Name));
      .ForMember(x => x.Important, opt => opt.MapFrom(y => y.ReplayProp));

如您所见,我真的想要:

Mapper.CreateMap<myObject, Context>()
      .ForMember(x => x.WellId, opt => opt.MapFrom(y => y.Id))
      .ForMember(x => x.Name, opt => opt.MapFrom(y => y.Name));
      .ForMember(x => x.Important, opt => opt.MapFrom(y => isOptionTrue? y.NormProp: y.ReplayProp));

问题:是的我有一个空的sublcass,因为我有两个独特的MyObject到Context映射。整件事看起来像是一个超级黑客的工作。我无法想象他们真的不支持这样的事情,但我不知所措。我不知道如何让我的bool随之而来。

1 个答案:

答案 0 :(得分:1)

也许我的想象力是有限的,但我个人认为“自动映射”的用途有限,除非在两个“相同”类之间进行映射。它不是更直接,更快速,更容易维护下面的代码吗?

var context = new Context {
    WellId = myObject.Id,
    Name = myObject.Name,
    Important = (isOptionTrue ? myObject.NormProp : myObject.ReplayProp)
};