I am using AutoMapper version 10.1.1 in .NET CORE 5 project. I have nested object that I need map but unable to do so and getting following exception although I can get data mapped for first child which in my case 'Enforcements' but cannot access to child of child Object 'Contraventions'
Class at Level 0
public class SiteContraventionDataView
{
public int SiteId { get; set; }
public string SiteName { get; set; }
public ICollection<EnforcementDataView> Enforcements { get; set; }
}
Child Class at level 1
public class EnforcementDataView
{
public int EnforcementId { get; set; }
public ICollection<ContraventionDataView> Contraventions { get; set; }
}
I am getting error when I try to set source for 'Contraventions' from above child class. I am trying to lambda expression to get Contravention object reference
.ForMember(dataView => dataView.Enforcements.Select(x=>x.Contraventions), opt => opt.MapFrom(dataModel => GetContraventions(dataModel.Enforcements.ToList())))
AutoMapping class
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;
}
}
CodePudding user response:
Try to add mappings for Enforcement
and Contravention
:
CreateMap<Enforcement, EnforcementDataView>();
CreateMap<Contravention, ContraventionDataView>();
CreateMap<Site, SiteContraventionDataView>();