自定义属性类型的自动映射器规则

时间:2018-10-08 11:56:51

标签: c# automapper

所以我有这个类TranslatedString:ListDictionary

public class TranslatedString {
    public string Language {get;set}

    public string Value {
        get {
            return this[Language] as string;
        }
        set {
            this[Language] = value;
        }
    }
    ....more complex logic in this class
}

和如下所示的目标类:

{
    public TranslatedString Name {get;set;}
    public TranslatedString Desc {get;set;}

    public void SetLanguage(string lang) {
       this.Name.Language = lang;
       this.Desc.Language = lang;
    }
}

现在,我想将这样的源映射到上面的目标:

{
    public string Language {get;set;}
    public string Name {get;set;}
    public string Desc {get;set;}
}

这是我的地图:

CreateMap<String, TranslatedString>(MemberList.None)
  .ForMember(x => x.Value, o => o.MapFrom(s => s));

CreateMap<Source, Dest>(MemberList.Source)
  .BeforeMap((s, d, context) {
      d.SetLanguage((string)context.Items["Language"]);
  });

这是我的地图方式:

var dest = Mapper.Map<Dest>(source, opt => opt.Items["Language"] = "en");

我遇到的问题是,当自动映射器映射字符串=> TranslatedString时,它将为每个TranslatedString创建一个新实例,这意味着在“ BeforeMap”中设置的“ Language”失去了它的值。如何解决这个问题并为所有类的所有String => TranslatedString映射保留通用解决方案?

0 个答案:

没有答案