Perhaps I found a potential solution for you - depending on how you want to use the allowOverride flag.
If you want the flag to work the same for all mappings, you can create a TypeConverter as follows
public class NullableIntConverter : ITypeConverter<int?, int?> { private bool AllowOverrides { get; set;} public NullableIntConverter(bool allowOverrides) { AllowOverrides = allowOverrides; } public int? Convert(ResolutionContext context) { var source = context.SourceValue as int?; var destination = context.DestinationValue as int?; if (destination.HasValue && !AllowOverrides) return destination; else return source; } }
Initialize it as follows:
Mapper.CreateMap<Sample1, Sample2>(); Mapper.CreateMap<int?, int?>().ConvertUsing(new NullableIntConverter(true)); Mapper.AssertConfigurationIsValid();
Now it checks the assignment for the value and redefines it depending on your constructor argument.
OR
If you want to configure it for each mapping, then you can use ValueResolver (note that this code can do with some additional verification):
public class NullableIntResolver : IValueResolver { public bool AllowOverrides { get; set; } public NullableIntResolver(bool allowOverrides) { AllowOverrides = allowOverrides; } public ResolutionResult Resolve(ResolutionResult source) {
Then you can initialize your mappings as follows:
var allowOverrides = true; Mapper.CreateMap<Sample1, Sample2>() .ForMember(dest => dest.Age, opt => opt.ResolveUsing<NullableIntResolver>() .FromMember(src => src.Age) .ConstructedBy(() => new NullableIntResolver(allowOverrides))) .ForMember(dest => dest.Number, opt => opt.ResolveUsing<NullableIntResolver>() .FromMember(src => src.Number) .ConstructedBy(() => new NullableIntResolver(allowOverrides))); Mapper.AssertConfigurationIsValid();
source share