簡體   English   中英

使用 AutoMapper,我如何 map 聚合根屬性到所有目標集合項屬性?

[英]Using AutoMapper, how do I map an aggregate root property to all destination collection item properties?

我創建了一個MRE ,它位於此處並可用

總之,我想將 Source class 的屬性 map 轉換為 Destination 屬性的多個列表項的屬性(它是列表類型)

這是來自 MRE 的示例

資源

using System.Collections.Generic;

namespace WebApplication1.Controllers
{
    public class OuterSource
    {
        public int ID { get; set; }

        public List<OuterSourceListItem> List { get; set; }

        public string OuterSourceProp1 { get; set; }// Notice how you can have prop on source which is not on dest, no complaints from AutoMapper there
    }
    public class OuterSourceListItem
    {
        public string Name { get; set; }

        public string Desc { get; set; }

    }
}

目的地

using System.Collections.Generic;

namespace WebApplication1.Models
{
    public class OuterDest
    {
        public int ID { get; set; }

        public List<OuterDestListItem> List { get; set; }
    }
    public class OuterDestListItem
    {
        public string Name { get; set; }

        public string Desc { get; set; }

        public int MyParentID { get; set; }

    }
}

映射器配置

    return new MapperConfiguration(cfg =>
    {
        cfg.AddProfile(new OuterSourceToOuterDest());
        cfg.AddProfile(new OuterSourceListItemToOuterDestListItem());
    });

輪廓

public class OuterSourceListItemToOuterDestListItem : Profile
{
    public OuterSourceListItemToOuterDestListItem()
    {
        CreateMap<OuterSourceListItem, OuterDestListItem>();
    }
}



  public class OuterSourceToOuterDest : Profile
    {
        public OuterSourceToOuterDest()
        {
            CreateMap<OuterSource, OuterDest>();
        }
    }

通過上述設置,這里是使用這些類的客戶端,包括實際的映射

[HttpGet]
public IActionResult Get()
{
    var inputModel = new OuterSource() { ID = 1};
    inputModel.List = new List<OuterSourceListItem>();
    inputModel.List.Add(new OuterSourceListItem() { Name = "aaa", Desc = "dddd" });
    var domain = _mapper.Map<OuterDest>(inputModel);

    return Ok(domain);
}

實際的 output 現在在左邊,下面是紅色的,想要的結果是右邊的綠色在此處輸入圖像描述

我需要 list.myParentID 值等於 OuterSource.ID 的值,您可以在此處看到在此處輸入圖像描述

幾乎就像我需要以某種方式在 OuterDest 內的屬性設置器/獲取器中以某種方式派生 MyParentID?

一種選擇是在映射之后立即使用方法調用 OuterDest 實例上的方法

AfterMap(Action<TSource, Tdestination> afterFunction)

成員映射后對源和/或目標類型執行自定義 function

在此處輸入圖像描述

在此處輸入圖像描述

暫無
暫無

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

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