通常在 API 我們會使用 DTO (資料傳輸物件),使用 Entity 來代表資料庫對應的物件,因為有些資料庫的欄位不會暴露給 API 知道,反過來也是。而在這之中的轉換相當麻煩,因為大部分欄位名稱都一樣,只有少部分要做調整,而這樣的轉換十分的無聊,不過我們可以使用 Mapster 這樣的套件來幫我們解決。
參考資料:
Github - Mapster
安裝
先使用 NuGet 安裝 Mapster 套件,或是使用 .NET CLI 執行以下指令安裝
dotnet add package Mapster
最簡單映射
假設 User 的 DTO 和 Entity 如下:
public class UserEntity
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
public class UserDto
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
產生新物件
兩個屬性名稱一模一樣,透過 Mapster 套件一行就可以將資料從左邊倒到右邊:
UserDto dto = new()
{
Id = 1,
Name = "test",
Email = "test@example.com",
};
UserEntity entity = dto.Adapt<UserEntity>();
放入已存在的物件
如果要放到已存在的物件中也是一行
UserDto dto = new()
{
Id = 1,
Name = "test",
Email = "test@example.com",
};
UserEntity entity = new()
{
Id = 0,
Name = "",
Email = "",
};
dto.Adapt(entity);
從 Dictionary 取得
就算來源是 Dictionary 也不用怕
Dictionary<string,string> dictionary = new()
{
{ "Id", "1" },
{ "Name", "test" },
{ "Email", "test@example.com" },
};
UserEntity entity = dictionary.Adapt<UserEntity>();
自訂映射規則
如果有特殊的規則也可以透過自訂映射規則的方式靈活定義資料轉換方式
TypeAdapterConfig<UserDto, UserEntity>
.NewConfig()
.NameMatchingStrategy(NameMatchingStrategy.Flexible) // 忽略屬性大小寫
.Ignore(dest => dest.Name) // 忽略 Name 屬性
.Map(entity => entity.Email, dto => dto.Email + ", ") ; // 將 Email 屬性的值加上 ", "
參考資料:
Github - Mapster
留言
張貼留言
如果有任何問題、建議、想說的話或文章題目推薦,都歡迎留言或來信: a@ruyut.com