Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper naming convention with underscore/PascalCase properties

Tags:

c#

automapper

I have 2 classes I want to map with Automapper:

namespace AutoMapperApp
{
    public class Class1
    {
        public string Test { get; set; }
        public string property_name { get; set; }
    }
}

namespace AutoMapperApp
{
    public class Class2
    {
        public string Test { get; set; }
        public string PropertyName { get; set; }
    }
}

This is my Automapper config:

using AutoMapper;

namespace AutoMapperApp
{
    public static class AutoMapperConfig
    {
        public static MapperConfiguration MapperConfiguration;

        public static void RegisterMappings()
        {
            MapperConfiguration = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Class1, Class2>();
                cfg.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
                cfg.DestinationMemberNamingConvention = new PascalCaseNamingConvention();
            });
        }
    }
}

According the Wiki of Automapper this should work: https://github.com/AutoMapper/AutoMapper/wiki/Configuration

But my unittest fails:

using Xunit;
using AutoMapperApp;

namespace AutoMapperTest
{
    public class Test
    {
        [Fact]
        public void AssertConfigurationIsValid()
        {
            AutoMapperConfig.RegisterMappings();
            AutoMapperConfig.MapperConfiguration.AssertConfigurationIsValid();
        }
    }
}

Exception:

AutoMapper.AutoMapperConfigurationException: 
Unmapped members were found. Review the types and members below.
Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type
=============================================
Class1 -> Class2 (Destination member list)
AutoMapperApp.Class1 -> AutoMapperApp.Class2 (Destination member list)

Unmapped properties:
PropertyName

Why?


1 Answers

With help from the AutoMapper project in GitHub:

Try the CreateMap after you set the convention.

public static void RegisterMappings()
{
    MapperConfiguration = new MapperConfiguration(cfg =>
    {
        cfg.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
        cfg.DestinationMemberNamingConvention = new PascalCaseNamingConvention();
        cfg.CreateMap<Class1, Class2>();
    });
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!