[英]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.