Automapper: How to leverage a custom INamingConvention?

前端 未结 2 1263
长情又很酷
长情又很酷 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条回答
  • 2020-12-21 17:39

    What about

    public class DATAMODELProfile : Profile
    {
        protected override void Configure()
        {
            Mapper.CreateMap<DATAMODEL, DATAMODEL>();
            Mapper.CreateMap<DATAMODEL, SOMETHINGELSE>();
            Mapper.CreateMap<DATAMODEL, DataModelDto>()
                .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.ID))
                .ForMember(dest => dest.FirstName, opt => opt.MapFrom(src => src.FIRST_NAME))
                .ForMember(dest => dest.ChildDataModels, opt => opt.MapFrom(src => src.CHILD_DATAMODELS));
        }
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题