我有以下课程:
public class OneToManySource {
public OneToManySource SourceChild { get;set; } // will sometimes be null
public int Value { get; set; }
}
public interface IDestination
{
}
public class ChildlessDestination: IDestination
{
public int DestValue { get; set; }
}
public class ChildedDestination: IDestination
{
public int DestValue { get; set; }
public IDestination DestinationChild { get; set; } // Never null. If it would be null, use a ChildlessDestination instead.
}
我想以明智的方式来回映射这些。如果某个来源有孩子,则会转到ChildedDestination。否则,它会转到ChildlessDestination。
我有以下,有效,但很难看。我想知道它是否可以清理干净。特别是,“ConstructUsing”完成了工作,但它似乎(可以理解)对AutoMapper的内部智能不透明。所以ReverseMap()没有用。而不是那样,我们坚持使用另外两个ReverseMap()调用,以及最后一个CreateMap()。
例如,从反向地图开始我会更好吗?
public MapperConfigurationExpression Configure(MapperConfigurationExpression expression) {
expression.CreateMap<OneToManySource, ChildedDestination>()
.ForMember(d => d.DestValue, cfg => cfg.MapFrom(s => s.Value))
.ForMember(d => d.DestinationChild, opt => opt.MapFrom(s => s.SourceChild))
.ReverseMap();
expression.CreateMap<OneToManySource, ChildlessDestination>()
.ForMember(d => d.DestValue, cfg => cfg.MapFrom(s => s.Value))
.ReverseMap();
expression.CreateMap<OneToManySource, IDestination>()
.ConstructUsing((source, context) =>
{
if (source.SourceChild == null) {
return context.Mapper.Map<ChildlessDestination>(source);
}
return context.Mapper.Map<ChildedDestination>(source);
});
expression.CreateMap<IDestination, OneToManySource>()
.ConstructUsing((source, context) =>
{
return context.Mapper.Map<OneToManySource>(source);
});
return expression;
}