public static IMappingExpression<TSource, TDestination> ChangeTracking<TSource, TDestination>(this IMappingExpression<TSource, TDestination> mappingExpression)
where TDestination : IChangeTrackingTest
{
if (mappingExpression == null)
throw new ArgumentNullException(nameof(mappingExpression));
mappingExpression
.ForMember(destination => destination.CreatedBy, options =>
{
options.Condition((source, destination) => string.IsNullOrEmpty(destination.CreatedBy));
options.MapFrom(source => "Name from identityFactory()");
})
.ForMember(destination => destination.CreatedAt, options =>
{
options.Condition((source, destination) => destination.CreatedAt == default(DateTime));
options.MapFrom(source => DateTime.Now);
});
return mappingExpression;
}
public class AutoMapperInit
{
public static IMapper Init()
{
MapperConfigurationExpression mapperConfigurationExpression = new MapperConfigurationExpression();
mapperConfigurationExpression.AddProfile(new AutoMapperProfile());
MapperConfiguration config = new MapperConfiguration(mapperConfigurationExpression);
config.AssertConfigurationIsValid();
return config.CreateMapper();
}
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
ShouldMapField = fieldInfo => true;
ShouldMapProperty = propertyInfo => true;
//works in 5.1.1 but doesn't work in 5.2.0 or 6.0.2
CreateMap<Aggregate, Entity>()
.ChangeTracking(); //EXTENSION METHOD!
//works in 5.1.1 and 5.2.0 with public setter and private setter, even if interface contains only property with get
//CreateMap<Aggregate, Entity>()
// .ForMember(destination => destination.CreatedBy, options =>
// {
// options.Condition((source, destination) => string.IsNullOrEmpty(destination.CreatedBy));
// options.MapFrom(source => "Name from identityFactory()");
// })
// .ForMember(destination => destination.CreatedAt, options =>
// {
// options.Condition((source, destination) => destination.CreatedAt == default(DateTime));
// options.MapFrom(source => DateTime.Now);
// });
CreateMap<Entity, Aggregate>()
;
}
public class Aggregate
{
public string Name
{
get;
set;
}
}
public class Entity : IChangeTracking
{
public string Name
{
get;
private set;
}
public string CreatedBy
{
get;
set;
}
public DateTime CreatedAt
{
get;
set;
}
}
public interface IChangeTracking
{
string CreatedBy
{
get;
}
DateTime CreatedAt
{
get;
}