Automapper 链/嵌套对象映射抛出异常
Posted
技术标签:
【中文标题】Automapper 链/嵌套对象映射抛出异常【英文标题】:Automapper chain / nested object mapping throw exception 【发布时间】:2021-11-06 00:29:23 【问题描述】:我在 .NET CORE 5 项目中使用 AutoMapper 版本 10.1.1。我有嵌套的对象,我需要映射但无法这样做并得到以下异常,尽管我可以为第一个孩子映射数据,在我的情况下为“强制”但无法访问子对象“违规”的孩子
0 级课程
public class SiteContraventionDataView
public int SiteId get; set;
public string SiteName get; set;
public ICollection<EnforcementDataView> Enforcements get; set;
1 级儿童班
public class EnforcementDataView
public int EnforcementId get; set;
public ICollection<ContraventionDataView> Contraventions get; set;
当我尝试从上面的子类设置“Contraventions”的来源时出现错误。我正在尝试使用 lambda 表达式来获取 Contravention 对象引用
.ForMember(dataView => dataView.Enforcements.Select(x=>x.Contraventions), opt => opt.MapFrom(dataModel => GetContraventions(dataModel.Enforcements.ToList())))
自动映射类
public class SiteContraventionsProfile : Profile
public SiteContraventionsProfile()
CreateMap<Site, SiteContraventionDataView>()
.ForMember(dataView => dataView.SiteId, opt => opt.MapFrom(dataModel => dataModel.SiteId))
.ForMember(dataView => dataView.SiteName, opt => opt.MapFrom(dataModel => dataModel.SiteName))
.ForMember(dataView => dataView.Enforcements, opt => opt.MapFrom(dataModel => dataModel.Enforcements))
.ForMember(dataView => dataView.Enforcements.Select(x=>x.Contraventions), opt => opt.MapFrom(dataModel => GetContraventions(dataModel.Enforcements.ToList())))
;
private List<Contravention> GetContraventions(List<Enforcement> enforcements)
List<Contravention> contraventions = new List<Contravention>();
if (enforcements.Any())
var t1 = enforcements.Select(x => x.EnforcementContraventions);
return contraventions;
【问题讨论】:
【参考方案1】:尝试为Enforcement
和Contravention
添加映射:
CreateMap<Enforcement, EnforcementDataView>();
CreateMap<Contravention, ContraventionDataView>();
CreateMap<Site, SiteContraventionDataView>();
【讨论】:
以上是关于Automapper 链/嵌套对象映射抛出异常的主要内容,如果未能解决你的问题,请参考以下文章
JsonSerializable - fromJson 在嵌套对象上抛出 _InternalLinkedHashMap<dynamic, dynamic> 异常