C# (自动映射)具有相同条件的多个映射冗余
我需要找到更好的解决方案:C# (自动映射)具有相同条件的多个映射冗余,c#,.net-core,automapper,C#,.net Core,Automapper,我需要找到更好的解决方案: public MappingProfile() { CreateMap<DesireDto, Desire>() .ForMember(x => x.CreationDate, x => x.Ignore()) .ForMember(x => x.ModifiedDate, x => x.Ignore()) .ForMember(x =&
public MappingProfile()
{
CreateMap<DesireDto, Desire>()
.ForMember(x => x.CreationDate, x => x.Ignore())
.ForMember(x => x.ModifiedDate, x => x.Ignore())
.ForMember(x => x.ModifiedUser, x => x.Ignore())
.ForMember(x => x.CreationUser, x => x.Ignore())
.ForMember(x => x.Language, x => x.Ignore());
CreateMap<ProductDto, Product>()
.ForMember(x => x.CreationDate, x => x.Ignore())
.ForMember(x => x.ModifiedDate, x => x.Ignore())
.ForMember(x => x.ModifiedUser, x => x.Ignore())
.ForMember(x => x.CreationUser, x => x.Ignore())
.ForMember(x => x.Language, x => x.Ignore());
}
我在这两方面都有相同的条件,但这看起来真的很难看
此线程导致无效:您可以尝试以下操作:
var map1 = CreateMap<DesireDto, Desire>();
var map2 = CreateMap<ProductDto, Product>();
foreach (var s in new []{nameof(DesireDto.CreationDate),nameof(DesireDto.ModifiedDate),nameof(DesireDto.ModifiedUser),nameof(DesireDto.CreationUser),nameof(DesireDto.Language)})
{
map1.ForMember(s,x=>x.Ignore()) ;
map2.ForMember(s,x=>x.Ignore()) ;
}
但是你应该听听FAL关于SRP的建议
如果希望和productd共享一些成员,也许您应该尝试使用基类或接口,并应用所需的忽略规则 您可以在根配置级别使用ForAllPropertyMaps。这使您可以筛选类型、名称空间、属性名称,然后忽略:
cfg.ForAllPropertyMaps(pm =>
pm.DestinationProperty.DeclaredType.Namespace == "Whatever" &&
pm.DestinationProperty.Name == "CreationDate",
(pm, opt) => opt.Ignore());
然后对所有要忽略的不同属性重复此操作。名称空间确保您只筛选特定名称空间中类型的目标成员,但您可以根据类型元数据执行任何操作。SRP是最好的选择。考虑到您已经分离了DTO,您可以控制小的更改。如果你把这些东西粘在一起,你就会开始违反SRP。它们是不同的东西,如果一个改变了,它不应该影响另一个。保持这样。有时代码重复是好事。它们不是相同的条件,它们是不同的条件,具有您命名的相同名称。他们的全名是DesireCreationDate/ProductCreationDate/等等。除非您的业务中有人同时处理DesireCreationDate/ProductCreationDate,否则抽象像IWithCreationDate这样的接口是毫无意义的。这将使他的生活更糟,因为他将失去在编译时计算属性更改的能力。也总是选择组合而不是继承。正如我所说的,有时代码重复会带来好结果。@Fals我同意younameof可以使用