zoukankan      html  css  js  c++  java
  • [非专业翻译] Mapster 配置嵌套映射

    [非专业翻译] Mapster - 配置嵌套映射

    系列介绍

    [非专业翻译] 是对没有中文文档进行翻译的系列博客,文章由机翻和译者自己理解构成,和原文相比有所有不同,但意思基本一致。

    因个人能力有限,如有谬误之处还请指正,多多包涵。

    正文

    本文将说明 Mapster 中的 嵌套映射

    映射配置

    例如有以下 父类、子类:

    public class ParentPoco
    {
        public string Id { get; set; }
        public List<ChildPoco> Children { get; set; }
        public string Name { get; set; }
    }
    public class ChildPoco
    {
        public string Id { get; set; }
        public List<GrandChildPoco> GrandChildren { get; set; }
    }
    public class GrandChildPoco
    {
        public string Id { get; set; }
    }
    

    如果你配置了父类型:

    TypeAdapterConfig<ParentPoco, ParentDto>.NewConfig()
        .PreserveReference(true);
    

    默认情况下,子类型不会从 PreserveReference 中得到效果。

    因此必须在 ParentPoco 中指定所有类型映射:

    TypeAdapterConfig<ParentPoco, ParentDto>.NewConfig()
        .PreserveReference(true);
    TypeAdapterConfig<ChildPoco, ChildDto>.NewConfig()
        .PreserveReference(true);
    TypeAdapterConfig<GrandChildPoco, GrandChildDto>.NewConfig()
        .PreserveReference(true);
    

    或者可以调用 全局配置实例 的 PreserveReference 方法:

    TypeAdapterConfig.GlobalSettings.Default.PreserveReference(true);
    

    Fork

    你可以使用 Fork 方法来定义仅将指定的映射应用于嵌套映射而不污染全局设置的配置:

    TypeAdapterConfig<ParentPoco, ParentDto>.NewConfig()
        .Fork(config => config.Default.PreserveReference(true));
    

    忽略为null或为空的字符串

    再比如,Mapster 只能忽略 null 值 (IgnoreNullValues),但是你可以使用 Fork 来忽略 null 或空值。

    TypeAdapterConfig<ParentPoco, ParentDto>.NewConfig()
        .Fork(config => config.ForType<string, string>()
            .MapToTargetWith((src, dest) => string.IsNullOrEmpty(src) ? dest : src)
        );
    
    目前学习.NET Core 最好的教程 .NET Core 官方教程 ASP.NET Core 官方教程
    如果您认为这篇文章还不错或者有所收获,您可以点击右下角的【推荐】支持,或请我喝杯咖啡【赞赏】,这将是我继续写作,分享的最大动力!
    声明:原创博客!请在转载时在文章开头注明本人博客地址。如发现错误,欢迎批评指正。凡是转载于本人的文章,不能设置打赏功能,如有特殊需求请与本人联系!
  • 相关阅读:
    SpringBoot中添加事务
    隐藏样式
    Mybatis配置解析
    题目1064:反序数------玩转小聪明
    题目1063:整数和
    题目1062:分段函数23333333333333
    题目1060:完数VS盈数------这题做得我想骂人
    题目1059:abc----------就喜欢这样的题
    题目1050:完数-----------runtime error的问题
    题目1049:字符串去特定字符
  • 原文地址:https://www.cnblogs.com/staneee/p/14913643.html
Copyright © 2011-2022 走看看