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?
public class AutoMapperConfig
{
public static void RegisterMappings()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Class1, Class2>();
cfg.SourceMemberNamingConvention = new LowerUnderscoreNamingConvention();
cfg.DestinationMemberNamingConvention = new PascalCaseNamingConvention();
});
}
}
I'm assuming you are calling this in your app_start method. AutoMapperConfig.RegisterMappings();
For organizational purposes you can separate your mappings into profiles, register them and set your conventions on a profile-by-profile basis if you don't need the convention to be global like in your example.
To answer your question, it looks like you created a mapper configuration but did not initialize it so Automapper doesn't know what mapping you're talking about.
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>();
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.