gpt4 book ai didi

c# - Automapper 基类映射

转载 作者:行者123 更新时间:2023-11-30 21:43:53 25 4
gpt4 key购买 nike

对于 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)));

RmsOelEntryUnlinkedPersonInputDtoRmsOelEntryUnlinkedAddressInputDto 都是从 RmsOelEntryInvolvedEntityBaseDto 继承的,这个基类具有属性 EffectiveFromTime >有效时间

我不希望必须重复映射 EffectiveFromTimeEffectiveToTime,如上所示。

但是,AddNewOELEntryInvolvedEntitiesUnlinkedInvolvedPersonUnlinkedAddNewOELEntryInvolvedEntitiesUnlinkedInvolvedAddressUnlinked 是自动生成的,没有基类。因此,我看不到如何使用 AutoMapper 的“包含”映射选项。

如何优化它以删除重复的映射?

最佳答案

我遇到了类似的情况,并求助于辅助扩展方法。我为您定制了:

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();

如果 AddNewOELEntryInvolvedEntitiesUnlinkedInvolvedAddressUnlinkedAddNewOELEntryInvolvedEntitiesUnlinkedInvolvedPersonUnlinked 是自动生成的,我会假设它们是部分的。

然后你可以为这些类创建通用接口(interface):

public interface IEffective 
{
DateTime EffectiveFromTime {get; set;}
DateTime EffectiveToTime {get; set;}
}

public partial AddNewOELEntryInvolvedEntitiesUnlinkedInvolvedAddressUnlinked
: IEffective { }

public partial AddNewOELEntryInvolvedEntitiesUnlinkedInvolvedPersonUnlinked
: IEffective { }

关于c# - Automapper 基类映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41261022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com