[非專業翻譯] 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
官方教程
如果您認為這篇文章還不錯或者有所收獲,您可以點選右下角的【推薦】支援,或請我喝杯咖啡【贊賞】,這将是我繼續寫作,分享的最大動力!
作者:玩雙截棍的熊貓
聲明:原創部落格!請在轉載時在文章開頭注明本人部落格位址。如發現錯誤,歡迎批評指正。凡是轉載于本人的文章,不能設定打賞功能,如有特殊需求請與本人聯系!