对于AutoMapper,我实现了以下工作,但重复映射代码:
cfg.CreateMap<RmsOelEntryUnlinkedPersonInputDto, AddNewOELEntryInvolvedEntitiesUnlinkedInvolvedPersonUnlinked>()
.ForMember(dest => dest.DateOfBirth, opts => opts.MapFrom(src => FormatDateType(src.DateOfBirth)))
.ForMember(dest => dest.EffectiveFromTime, opts => opts.MapFrom(src => FormatDateTimeType(src.EffectiveFromTime)))
.ForMember(dest => dest.EffectiveToTime, opts => opts.MapFrom(src => FormatDateTimeType(src.EffectiveToTime)));
cfg.CreateMap<RmsOelEntryUnlinkedAddressInputDto, AddNewOELEntryInvolvedEntitiesUnlinkedInvolvedAddressUnlinked>()
.ForMember(dest => dest.EffectiveFromTime, opts => opts.MapFrom(src => FormatDateTimeType(src.EffectiveFromTime)))
.ForMember(dest => dest.EffectiveToTime, opts => opts.MapFrom(src => FormatDateTimeType(src.EffectiveToTime)));
RmsOelEntryUnlinkedPersonInputDto
和RmsOelEntryUnlinkedAddressInputDto
都继承自RmsOelEntryInvolvedEntityBaseDto
,此基类的属性为EffectiveFromTime
和EffectiveToTime
。
我不希望如上所示重复映射EffectiveFromTime
和EffectiveToTime
。
但是,AddNewOELEntryInvolvedEntitiesUnlinkedInvolvedPersonUnlinked
和AddNewOELEntryInvolvedEntitiesUnlinkedInvolvedAddressUnlinked
是自动生成的,并且没有基类。因此,我不知道如何使用AutoMapper&#34; Include&#34;映射选项。
如何对此进行优化以删除重复的映射?
答案 0 :(得分:3)
我有类似的情况,并采用了辅助扩展方法。我根据你的情况定制:
internal static class CommonMapperExtensions
{
internal static IMappingExpression<TSource, TDestination> MapCommonFields<TSource, TDestination>(this IMappingExpression<TSource, TDestination> m)
where TSource : RmsOelEntryInvolvedEntityBaseDto
where TDestination : IEffective
{
return m
.ForMember(dest => dest.EffectiveFromTime, opts => opts.MapFrom(src => FormatDateTimeType(src.EffectiveFromTime)))
.ForMember(dest => dest.EffectiveToTime, opts => opts.MapFrom(src => FormatDateTimeType(src.EffectiveToTime)));
}
}
然后配置如下:
cfg.CreateMap<RmsOelEntryUnlinkedPersonInputDto, AddNewOELEntryInvolvedEntitiesUnlinkedInvolvedPersonUnlinked>()
.MapCommonFields()
.ForMember(dest => dest.DateOfBirth, opts => opts.MapFrom(src => FormatDateType(src.DateOfBirth)));
cfg.CreateMap<RmsOelEntryUnlinkedAddressInputDto, AddNewOELEntryInvolvedEntitiesUnlinkedInvolvedAddressUnlinked>()
.MapCommonFields();
如果AddNewOELEntryInvolvedEntitiesUnlinkedInvolvedAddressUnlinked
和AddNewOELEntryInvolvedEntitiesUnlinkedInvolvedPersonUnlinked
是自动生成的,我会认为它们是偏袒的。
然后你可以为这些类建立通用接口:
public interface IEffective
{
DateTime EffectiveFromTime {get; set;}
DateTime EffectiveToTime {get; set;}
}
public partial AddNewOELEntryInvolvedEntitiesUnlinkedInvolvedAddressUnlinked
: IEffective { }
public partial AddNewOELEntryInvolvedEntitiesUnlinkedInvolvedPersonUnlinked
: IEffective { }
答案 1 :(得分:0)
public class TBaseModel
{
public void ConfigureMapFrom(IMappingExpression<TEntity, TBaseModel> mapping)
{
// ... mappings
}
}
public class TModel : TBaseModel
{
public void ConfigureMapFrom(IMappingExpression<TEntity, TModel> mapping)
{
mapping.IncludeBase<TEntity, TBaseModel>();
// ... other mappings
}
}