I am using mapping by convention and have issues when adding profile to the configuration. Consider configuration below. I am using AutoFac to resolve profiles in CoreMapper and the profiles are correctly injected.
Mapping configuration
public CoreMapper(IEnumerable<Profile> profiles)
{
MapperConfiguration = new MapperConfiguration(cfg =>
{
cfg.CreateMissingTypeMaps = true;
cfg.AllowNullCollections = true;
cfg.AllowNullDestinationValues = true;
cfg.ForAllMaps((mapType, mapperExpression) =>
{
mapperExpression.PreserveReferences();
mapperExpression.MaxDepth(10);
});
cfg.IgnoreUnmapped();
foreach (var profile in profiles)
{
cfg.AddProfile(profile);
}
cfg.CreateMap<string, string>().ConvertUsing(str => string.IsNullOrEmpty(str) ? null : str);
});
Mapper = MapperConfiguration.CreateMapper();
}
IgnoreUnmapped is as follows:
private static void IgnoreUnmappedProps(TypeMap map, IMappingExpression expression)
{
foreach(var propName in map.GetUnmappedPropertyNames())
{
if (map.SourceType.GetProperty(propName) != null)
expression.ForSourceMember(propName, opt => opt.Ignore());
if (map.DestinationType.GetProperty(propName) != null)
expression.ForMember(propName, opt => opt.Ignore());
}
}
public static void IgnoreUnmapped(this IProfileExpression profile)
{
profile.ForAllMaps(IgnoreUnmappedProps);
}
In my code I have a generic class implementation with the line like this:
mapper.Map<TPoco>(entity);
Note: mapper is an instance of CoreMapper from above. where TPoco is POCO model defined like:
public class ModelPoco : IModel {
// props
}
and entity is database entity model.
The mapping works fine. The result of mapper.Map< TPoco>(entity) is correct.
I then proceed and add a profile for a specific map that is not at all related to the ModelPoco being mapped before.
The profile being added:
public class RepositoryLayerProfile : AutoMapper.Profile {
public RepositoryLayerProfile() {
CreateMap<SomeOtherEntity, ISomeOtherModelInterface>();
}
}
Version: 6.2.2
Expected behavior
Mapping of ModelEntity to ModelPoco should happen normally.
Actual behavior
The mapping breaks with the message: Unable to cast object of type 'Proxy< IModel>' to type 'ModelPoco'. on line mapper.Map(entity);
I am not sure why does it create Proxy class for IModel interface and then tries to cast to concrete implementation? I explicitly set that I want to map entity to a concrete implementation.
If I remove CreateMap from the profile it works fine, but the first time I define CreateMap in the said profile, it breaks. It seems to me like it forgets about the configuration for some reason even tho it has nothing to do with it.