所有成员的 Automapper 规范化

Ren*_*ene 3 c# automapper

是否有一些简短的方法可以在所有字符串类型属性上使用规范化方法?

例如我有两个类:

public class Text
{
    public string Header { get; set; }
    public string Content { get; set; }
}

public class TextSource
{
    public string Header { get; set; }
    public string Content { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我希望他们映射:

[TestMethod]

    public void ShouldMapTextSourceToText()
    {
        var TextSource = new TextSource()
        {
            Content = "<![CDATA[Content]]>",
            Header = "<![CDATA[Header]]>",
        };

        Mapper.Initialize(cfg => cfg.CreateMap<TextSource, Text>()
            .ForMember(dest => dest.Content, opt => opt.MapFrom(s => s.Content.Normalize()))
            .ForMember(dest => dest.Header, opt => opt.MapFrom(s => s.Header.Normalize())));

        var text = Mapper.Map<Text>(TextSource);

        Assert.AreEqual("Content", text.Content);
        Assert.AreEqual("Header", text.Header);           
    }
Run Code Online (Sandbox Code Playgroud)

不是为每个属性单独配置规范化方法,是否可以对所有属性执行一次?

stu*_*rtd 5


是的,您将使用自定义类型转换器:

Mapper.Initialize(cfg => {
        cfg.CreateMap<TextSource, Text>();
        cfg.CreateMap<string, string>().ConvertUsing(s => s.Normalize());
});
Run Code Online (Sandbox Code Playgroud)

这告诉 AutoMapper,每当它将字符串映射到字符串时,就应用该Normalize()方法。

请注意,这将适用于所有字符串转换,而不仅仅是TextSourcetoText映射中的那些。