簡體   English   中英

AutoMapper,將一種類型映射到兩種不同的類型

[英]AutoMapper, mapping one type in two different types

我有以下型號:

public class Stuff
{
    ...
    public IList<Place> Places { get; set; } = null!;
    ...
}

public class Place
{
    ...
    public IList<Stuff> Stuffs { get; set; } = null!;
    ...
}

public class StuffEntity 
{
    ...
    public IList<PlaceStuffEntity> Places { get; set; } = null!;
    ...
}

public class PlaceEntity 
{
    ...
    public IList<PlaceStuffEntity> Stuffs { get; set; } = null!;
    ...
}

public class PlaceStuffEntity
{
    public int StuffId { get; private set; }
    public StuffEntity Stuff { get; set; } = null!;
    public int PlaceId { get; private set; }
    public PlaceEntity Place { get; set; } = null!;
}

cfg.CreateMap<StuffEntity, Stuff>()
   .ForMember(d => d.Places,
              opt => opt.MapFrom(s => s.Places.Select(y => y.Place).ToList()));
cfg.CreateMap<PlaceEntity, Place>()
   .ForMember(d => d.Stuffs,
              opt => opt.MapFrom(s => s.Places.Select(y => y.Stuff).ToList()));
cfg.CreateMap<PlaceAndStuffEntity, Stuff>()              // < -- Issue
   .IncludeMembers(entity=> entity.Stuff);
cfg.CreateMap<PlaceAndStuffEntity, Place>()              // < -- Issue
   .IncludeMembers(entity=> entity.Place);

由於某種原因,當我添加最后兩行時,轉換不起作用......

但是,如果我只添加一行,例如用於轉換PlaceAndStuffEntity -> Stuff僅適用於PlaceEntity -> Place一種轉換

var place = mapper.Map<Place>(placeEntity); // <- This works
var stuff = mapper.Map<Stuff>(stuffEntity); // <- Does not work !!

有沒有辦法正確處理以下轉換?

聽起來您想通過連接表 (PlaceAndStuff) 映射到其他實體類型。 例如,在您的 Place 中獲取 Stuff 列表,Stuff 中獲取 Place 列表,您希望指示 Automapper 如何在連接表中導航。

例如:

cfg.CreateMap<StuffEntity, Stuff>()             
   .ForMember(x => x.Places, opt => opt.MapFrom(src => src.PlaceEntity));
// Where StuffEntity.Places = PlaceAndStuffEntities, to map Stuff.Places use PlaceAndStuffs.PlaceEntity

cfg.CreateMap<PlaceEntity, Place>()             
   .ForMember(x => x.Stuffs, opt => opt.MapFrom(src => src.StuffEntity));

因此,與其試圖告訴 EF 如何映射連接實體 PlaceStuffEntity,我們專注於 PlaceEntity 和 StuffEntity,並告訴 Automapper 導航連接實體以通過連接實體獲取實際的 Stuff 和 Place 親屬。

改變

cfg.CreateMap<PlaceEntity, Place>()
   .ForMember(d => d.Stuffs,
              opt => opt.MapFrom(s => s.Places.Select(y => y.Stuff).ToList()));

cfg.CreateMap<PlaceEntity, Place>()
   .ForMember(d => d.Stuffs,
              opt => opt.MapFrom(s => s.Stuffs.Select(y => y.Stuff).ToList()));

源類型 PlaceEntity 沒有名為 Places 的屬性,只有 Stuffs。

暫無
暫無

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

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