簡體   English   中英

.NET Core Automapper 相同類型的不同映射

[英].NET Core Automapper different mappings for same types

我正在使用 ASP.NET Core 和AutoMapper.Extensions.Microsoft.DependencyInjection並通過調用services.AddAutoMapper(typeof(Startup));來初始化 Automapper .

我創建如下映射:

public class ItemProfile : Profile
{
    public ItemProfile()
    {
        CreateMap<ItemDto, Item>();
    }
}

我的 API 中有兩種方法:一種用於創建項目,一種用於更新項目。 我想使用相同的 DTO 進行創建和更新,但忽略 create 方法的itemId

所以我嘗試將.ForMember(x => x.itemId, option => option.Ignore())用於 create 方法,但不用於 update 方法。

現在我可以為每個創建/更新請求創建一個新的映射器實例,但由於性能原因我想使用依賴注入。 有沒有人有一些想法和想法如何處理這個問題?

我假設在更新情況下,源 ID 將是非空或非零(取決於是字符串還是 int ID),對於創建情況,ID 將是 null 或零。

如果這是一個有效的指南,您可以讓您的映射在兩種情況下都復制值。

如果這不是一個足夠好的指南,您可以在映射之前正確設置 DTO ID,並允許復制(回到我上面所說的),或者向您的 DTO 添加一個附加屬性,指定它是更新還是創建案例,並將其用作 map 中的條件。 像這樣的 DTO(用字符串 ID 顯示;您可以適應 int)。

class ItemDto
{
    string itemId { get; set; }
    bool IsForCreate { get; set; }
}

這個映射在這兩種情況下都忽略了復制,但后來在映射更新情況后更正了它:

.ForMember(x => x.itemId, option => option.Ignore())
.AfterMap((source, dest) => { if (!source.IsForCreate) dest.itemId = source.itemId; });

您可能會爭辯說后一種解決方案會污染您的 DTO,但我會爭辯說“誰在乎,它是一個 DTO!” 關鍵是在映射之前,您必須在映射之前正確設置IsForCreate

對於不同的操作,通常會創建多個 DTO。 此方法還通過僅使用您希望客戶端為其提供值的字段定義更嚴格的 DTO 來防止過度發布或批量分配。

在您的情況下,將有 CreateItemDto 和 UpdateItemDto DTO,它們將具有不同的字段集,並且兩者都將映射到一個內部實體。

例如:

class CreateItemDto
{
    [JsonPropertyName("id")]
    public Guid Id { get; set; }

    [JsonPropertyName("type")]
    public string ItemType { get; set; }
}

class UpdateItemDto
{
    [JsonPropertyName("type")]
    public string ItemType { get; set; }
}

class ItemMappingProfile : Profile
{
    public ItemMappingProfile()
    {
        CreateMap<CreateItemDto, Item>();
        CreateMap<UpdateItemDto, Item>();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM