在 AutoMappingProfiles 中我有这样的地图
CreateMap<Order, OrderDto>()
.ForMember(destination => destination.Name, options =>
{
...
})
.ForMember(destination => destination.Points, options =>
{
...
})
Order
和OrderDto
都具有相同的属性、相同的类型和名称,除了少数具有复杂类型之外,因此我使用.ForMember
来处理它们。
现在我想将此映射逻辑移至单独的转换器类中,然后在映射器中我可以像这样替换它
CreateMap<Order, OrderDto>().ConvertUsing(new OrderModelTypeConverter());
我想这样做,因为我需要在同一解决方案中使用相同的映射到不同的项目。
我开始写一个转换器:
public class OrderModelTypeConverter : ITypeConverter<OrderEntity, Order>
{
public OrderDto Convert(Order order, OrderDto orderDto, ResolutionContext context)
{
///how to access to CreateMap ??
.ForMember(destination => destination.Name, options =>
{
...
})
.ForMember(destination => destination.Points, options =>
{
...
})
return result;
}
}
如何访问转换器内的CreateMap? 我想使用相同的逻辑,其中自动映射器自动映射具有相同类型和名称的属性,对于特殊的属性,我将简单地使用
.ForMember
但我找不到如何在转换器中执行此操作的方法
我想这样做,因为我需要在同一解决方案中使用相同的映射到不同的项目。
不是直接的答案,但可以说更简单的方法是将配置移动到某种扩展方法:
public static class ExprExt
{
public static IMappingExpression<Order, OrderDto> ConfigureOrderModelTypeMapping(this IMapperConfigurationExpression e) => e.CreateMap<Order, OrderDto>()
.ForMember(destination => destination.Name, options => { })
.ForMember(destination => destination.Points, options => { });
}
var configuration = new MapperConfiguration(e =>
{
e.ConfigureOrderModelTypeMapping();
});
或者甚至更好 - 使用内置方法进行模块化配置与
Profile
的:
public class OrderModelProfile : Profile
{
public OrderModelProfile()
{
CreateMap<Order, OrderDto>()
.ForMember(destination => destination.Name, options => { })
.ForMember(destination => destination.Points, options => { });
}
}
var configuration = new MapperConfiguration(e =>
{
e.AddProfile<OrderModelProfile>(); // or use assembly scanning
});