天天看點

[非專業翻譯] Mapster - 使用特性标簽配置映射

[非專業翻譯] Mapster - 使用特性标簽配置映射

系列介紹

[非專業翻譯] 是對沒有中文文檔進行翻譯的系列部落格,文章由機翻和譯者自己了解構成,和原文相比有所有不同,但意思基本一緻。

因個人能力有限,如有謬誤之處還請指正,多多包涵。

正文

本文将說明 Mapster 的 特性标簽配置映射

AdaptIgnore 特性

當一個屬性有

[AdaptIgnore]

标記時,這個屬性将不會被映射:

public class Product {
    public string Id { get; set; }
    public string Name { get; set; }

    [AdaptIgnore]
    public decimal Price { get; set; }
}
           

當一個成員有

[AdaptIgnore]

标記時,不管是 源到目标 還是 目标到源 的映射都将會忽略這個成員,可以使用

MemberSide

指定單方的忽略。

例如,隻有

Product

當作 源映射時,

Price

字段才會被忽略:

public class Product {
    public string Id { get; set; }
    public string Name { get; set; }

    [AdaptIgnore(MemberSide.Source)]
    public decimal Price { get; set; }
}
           

忽略自定義的 Attribute

Mapster 還支援忽略标記了任何 Attribute 的屬性,使用

IgnoreAttribute

方法指定要忽略的 Attribute 。

例如,忽略所有标記了

JsonIgnoreAttribute

的屬性:

TypeAdapterConfig.GlobalSettings.Default
    .IgnoreAttribute(typeof(JsonIgnoreAttribute));
           

IgnoreAttribute

的映射配置會在 源到目标 和 目标到源 時生效,如果隻想在單方生效,可以使用

IgnoreMember

方法實作:

config.IgnoreMember((member, side) => member.HasCustomAttribute(typeof(NotMapAttribute)) && side == MemberSide.Source);
           

AdaptMember 特性标記

映射到不同的名稱

使用

[AdaptMember]

特性标記可以實作修改映射的名稱。

例如,将

Id

映射為

Code

:

public class Product {
    [AdaptMember("Code")]
    public string Id { get; set; }
    public string Name { get; set; }
}
           

映射非公開成員

[AdaptMember]

特性标記可以實作映射非公開成員:

public class Product {
    [AdaptMember]
    private string HiddenId { get; set; }
    public string Name { get; set; }
}
           

根據自定義屬性重命名成員

Mapster 支援重寫成員的名稱,通過

GetMemberName

方法可實作。

例如,通過在類的屬性上标記

JsonProperty

特性指定屬性名稱:

TypeAdapterConfig.GlobalSettings.Default
    .GetMemberName(member => member.GetCustomAttributes(true)
                                    .OfType<JsonPropertyAttribute>()
                                    .FirstOrDefault()?.PropertyName);  //if return null, property will not be renamed
           
注意!如果

GetMemberName

傳回結果為空,那麼将不會重寫成員名稱

包括自定義 Attribute

可以使用

IncludeAttribute

實作根據成員擁有的标記特性來映射非公開的成員。

例如,映射所有标記了

JsonPropertyAttribute

的非公開成員:

TypeAdapterConfig.GlobalSettings.Default
    .IncludeAttribute(typeof(JsonPropertyAttribute));
           

目标值

[UseDestinationValue]

特性标記可以讓 Mapster 使用現有的值來做映射,而不是建立執行個體化新對象。

例如下面的例子,

Items

屬性預設為

new List<OrderItem>()

,使用

UseDestinationValue

Items

在映射時不會建立新對象,而是直接使用已經執行個體化的集合對象:

public class Order {
    public string Id { get; set; }

    [UseDestinationValue]
    public ICollection<OrderItem> Items { get; } = new List<OrderItem>();
}
           

目前學習.NET Core 最好的教程

.NET Core 官方教程

ASP.NET Core

官方教程

如果您認為這篇文章還不錯或者有所收獲,您可以點選右下角的【推薦】支援,或請我喝杯咖啡【贊賞】,這将是我繼續寫作,分享的最大動力!

作者:玩雙截棍的熊貓

聲明:原創部落格!請在轉載時在文章開頭注明本人部落格位址。如發現錯誤,歡迎批評指正。凡是轉載于本人的文章,不能設定打賞功能,如有特殊需求請與本人聯系!