如果使用命名约定,则Automapper会省略CreateMap

时间:2018-10-26 13:00:43

标签: c# automapper

基于this问题,我想知道是否可以省略CreateMap<PERSON, Person>();

我正在使用Automapper 7.0.1,配置文件具有以下格式

public class AutoMapperProfile : Profile
{
    public AutoMapperProfile()
    {
        //...
        //...

        SourceMemberNamingConvention = new UpperUnderscoreNamingConvention();
        DestinationMemberNamingConvention = new PascalCaseNamingConvention();
        CreateMap<PERSON, Person>(); //what I want to omit

    }
}

我注意到,如果删除此行CreateMap<PERSON, Person>();,则仅映射不包含任何下划线的属性,并且映射器会抛出异常,并显示消息,其中包含未映射的属性和它们的列表。

为什么仅基于命名约定来映射所有属性,为什么要使用CreateMap

编辑:

@Lucian回答后,我从Profile中删除了命名约定,并在初始化时将其添加到了

Mapper.Initialize(cfg =>
{
    cfg.AddProfile<AutoMapperProfile>();
    cfg.SourceMemberNamingConvention = new UpperUnderscoreNamingConvention();
    cfg.DestinationMemberNamingConvention = new PascalCaseNamingConvention();
});

现在我不必使用CreateMap

1 个答案:

答案 0 :(得分:0)

默认地图(如果您省略CreateMap,则由AM创建的默认地图)是全局的,它肯定不在您创建的配置文件中。因此,在个人资料上设置命名约定无济于事。在全局配置上设置命名约定。