【问题标题】:(Automapper) Multiple Maps with same Conditions redundancy(Automapper)具有相同条件冗余的多个地图
【发布时间】:2018-04-17 12:31:41
【问题描述】:

我需要找到更好的解决方案:

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

我的条件相同,但这看起来真的很丑

这个帖子什么都没有:https://github.com/AutoMapper/AutoMapper/issues/2236

【问题讨论】:

  • SRP 是最好的。鉴于您已经分离了 DTO,您可以控制小的更改。如果你把这些东西粘在一起,你就会开始违反 SRP。它们是不同的东西,如果一个改变,它不应该影响另一个。就这样保持吧。有时代码重复是有好处的。
  • 它们不是相同的条件,它们是具有相同名称的不同条件(您命名它们)。它们的全名是 DesireCreationDate/ProductCreationDate/etc。除非您的业务中的某个地方一起处理 DesireCreationDate/ProductCreationDate,否则抽象像 IWithCreationDate 这样的接口是毫无价值的。

标签: c# .net-core automapper


【解决方案1】:

您可以在根配置级别使用 ForAllPropertyMaps。这使您可以过滤类型、命名空间、属性名称,然后忽略:

cfg.ForAllPropertyMaps(pm => 
    pm.DestinationProperty.DeclaredType.Namespace == "Whatever" && 
    pm.DestinationProperty.Name == "CreationDate", 
    (pm, opt) => opt.Ignore());

然后对您要忽略的所有不同属性重复此操作。命名空间确保您只过滤特定命名空间中类型的目标成员,但您可以根据类型元数据做任何您想做的事情。

【讨论】:

    【解决方案2】:

    你可以试试这个:

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

    但你应该听听 Fals 关于 SRP 的建议。

    如果DesireDtoProductDto 共享一些成员,也许你应该尝试拥有一个基类或接口,并应用你想要的忽略规则。

    【讨论】:

    • 这将使他的生活更加糟糕,因为他将失去在编译时找出属性变化的能力。也总是选择组合而不是继承。正如我所说,有时代码重复是有好处的。
    • @Fals 我同意你的看法
    • nameof()可以用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多