[英]Using AutoMapper, how do I map an aggregate root property to all destination collection item properties?
總之,我想將 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?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.