[英]Map nested object with Automapper in C#
我在我的 .NET Core 項目中使用了最新版本的 AutoMapper 10.1.1。 我有一個簡單的數據庫,用於以我想學習的語言學習新單詞。 我有以下表格:
在Words中有一個單詞的 ID,在WordExamples中,我引用此ID來鏈接該單詞的示例。 在WordExampleTranslation 中,我引用了WordExamples的ID ,以便用我的語言進行翻譯(只是為了理解示例的含義)。 每個表都有很多列,例如CreatedAt 、 CreatedBy等。
使用 Entity Framework Core,我根據單詞 ID 讀取這些數據,並且我只想返回到 UI 中的基本字段。
public IQueryable<WordExample> GetAllByWordId(long wordId)
{
return _db.WordExamples
.Include(c => c.Word)
.Include(c => c.Translations)
.Where(r => r.WordId == wordId);
}
為此,我為基本信息創建了 2 個類
public class BaseWordExample
{
public long LanguageId { get; set; }
public long WordId { get; set; }
public string Example { get; set; }
public IEnumerable<BaseWordExampleTranslation> Translations { get; set; }
}
public class BaseWordExampleTranslation
{
public long LanguageId { get; set; }
public long WordId { get; set; }
public long DestinationLanguageId { get; set; }
public string TraslationExample { get; set; }
}
然后,我有AutoMapper的MappingProfile
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<WordExample, BaseWordExample>()
.ReverseMap();
CreateMap<WordExampleTranslation, BaseWordExampleTranslation>()
.ReverseMap();
}
}
然后,我有一個 API
public async Task<IActionResult> GetAllAsync(long wordId)
{
var list = _localDb.GetAllByWordId(wordId);
var model = _mapper.Map<List<BaseWordExample>>(list);
return model != null ? Ok(model) : NotFound();
}
我希望收到一個映射到基本類的json ,其中包含來自WordExamples及其依賴表WordExampleTranslation的所有數據。 我所擁有的只是WordExamples值。 AutoMapper 無法識別字段Translations 。
[
{
"id": 1,
"language": 5,
"wordId": 1,
"example": "Eu parto para Inglaterra",
"exampleHtml": "<i>Eu</i> <b>parto</b> para Inglaterra"
}
]
然后,我嘗試更改MappingProfile
如下
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<WordExample, BaseWordExample>()
.ForMember(dest => dest.Translations,
act => act.MapFrom(src => src.Translations))
.ReverseMap();
CreateMap<WordExampleTranslation, BaseWordExampleTranslation>()
.ReverseMap();
}
}
但在這種情況下,我得到了這個錯誤
System.Reflection.TargetInvocationException:調用的目標已引發異常。 ---> System.MissingMethodException:找不到方法:'System.Collections.Generic.IEnumerable`1<WB.Domain.Base.BaseWordExampleTranslation> WB.Domain.Base.BaseWordExample.get_Translations()'。
試試這個
public async Task<IActionResult> GetAllAsync(long wordId)
{
var list = _localDb.GetAllByWordId(wordId);
var model = _mapper.Map<List<BaseWordExample>, List<WordExample>>(list);
return model != null ? Ok(model) : NotFound();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.