Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 所有成员的自动映射规范化_C#_Automapper - Fatal编程技术网

C# 所有成员的自动映射规范化

C# 所有成员的自动映射规范化,c#,automapper,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; } } 我想让他们

在所有字符串类型属性上使用规范化方法有什么捷径吗

例如,我有两门课:

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; }
}
我想让他们映射:

[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);           
    }
[TestMethod]
public void应为mapTextSourceToText()
{
var TextSource=new TextSource()
{
Content=“”,
标题=”,
};
初始化(cfg=>cfg.CreateMap())
.FormMember(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(TextSource);
Assert.AreEqual(“内容”,text.Content);
Assert.AreEqual(“Header”,text.Header);
}
是否可以对所有属性执行一次规范化操作,而不是单独为每个属性配置规范化方法?


是的,您将使用:

Mapper.Initialize(cfg=>{
CreateMap();
CreateMap().ConvertUsing(s=>s.Normalize());
});
这告诉AutoMapper,无论何时将字符串映射到字符串,都要应用
Normalize()
方法

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

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