Automapper: How to leverage a custom INamingConvention?

前端 未结 2 1268
长情又很酷
长情又很酷 2020-12-21 17:22

I am working with a database where the designers really seemed to enjoy capital letters and the underscore key. Since I have a simple ORM, my data models use these names as

2条回答
  •  梦毁少年i
    2020-12-21 17:40

    Create your mappings in profiles, and define the INamingConvention parameters as appropriate.

    I don't like the global/static, so I prefer using Initialize and define all of my mappings together. This also has the added benefit of allowing a call to AssertConfiguration... which means if I've borked my mapping I'll get the exception at launch instead of whenever my code gets around to using the problematic mapping.

    Mapper.Initialize(configuration =>
    {
        configuration.CreateProfile("Profile1", CreateProfile1);
        configuration.CreateProfile("Profile2", CreateProfile2);
    });
    Mapper.AssertConfigurationIsValid();
    

    in the same class with that initialization method:

    public void CreateProfile1(IProfileExpression profile)
    {
        // this.CreateMap (not Mapper.CreateMap) statements that do the "normal" thing here
        // equivalent to Mapper.CreateMap( ... ).WithProfile("Profile1");
    }
    
    public void CreateProfile2(IProfileExpression profile)
    {
        profile.SourceMemberNamingConvention = new PascalCaseNamingConvention();
        profile.DestinationMemberNamingConvention = new LowerUnderscoreNamingConvention();
    
        // this.CreateMap (not Mapper.CreateMap) statements that need your special conventions here
        // equivalent to Mapper.CreateMap( ... ).WithProfile("Profile2");
    }
    

    if you do it this way, and don't define the same mapping in both profiles, I don't think you need anything to "fill in the blank" from the original question, it should already be setup to do the right thing.

提交回复
热议问题