Search code examples
entity-framework-coreautomapperef-core-3.1automapper-10

Automapper.ProjectTo() is throwing null reference exception


I Have the following mapping :

        CreateMap<PeopleForm, FormDto>()
            .ForMember(des => des.Code, src => src.MapFrom(s => s.Code))
            .ForMember(des => des.Notes, src => src.MapFrom(s => s.FormNotes))
            //other mappings removed for breivity
            ;

        CreateMap<FormNote, NoteDto>()
            .ForMember(x => x.Note, cfg => cfg.MapFrom(y => y.Note));

and i want to query it :

        var query = _context.PeopleForms.Where(i => i.Id == id);
        var form = await _mapper.ProjectTo<FormDto>(query).FirstOrDefaultAsync();-->NullReferenceException

but it works when i comment out the mapping from FormNotes to Notes:

        CreateMap<PeopleForm, FormDto>()
            .ForMember(des => des.Code, src => src.MapFrom(s => s.Code))
            //.ForMember(des => des.Notes, src => src.MapFrom(s => s.FormNotes))--> this line is the problem
             ;

and, the work around solution i came up with was to to a select in the mapping:

                .ForMember(des => des.Notes, src => src.MapFrom(s => s.FormNotes.Select(n=> new 
                 NoteDto{Note = n.Note})))

i checked in the logs and it seems the issue is related mostly to Ef core :

             Microsoft.EntityFrameworkCore.Query: Error: An exception occurred while iterating over 
             the results of  a query for context type 'Backend.Infrastructure.MolsaContext'.

What should I do ? I have the exact mapping with another table(entity) and it works no problem, the only problem is with this particular mapping.

what am I missing? is the related to AutoMapper or Ef core?


Solution

  • So it was a miskate my side, the navigation property names of the FormNote and the NoteDto where the same which caused the null .

    CreateMap<FormNote, NoteDto>()
    .ForMember(x => x.Note, cfg => cfg.MapFrom(y => y.Note))
    .ForMember(x => x.LastModifiedAt, cfg => cfg.MapFrom(y => y.LastModifiedById != null ? y.ModifiedDate.Value.ToString("yyyy-MM-dd HH:m:s") : null))
    .ForMember(x => x.CreatedAt, cfg => cfg.MapFrom(y => y.CreatedDate.ToString("yyyy-MM-dd HH:m:s")))
    
    .ForMember(x => x.CreatedBy, cfg => cfg.MapFrom(y => y.CreatedBy.FullName))
    .ForMember(x => x.LastModifiedBy, cfg => cfg.MapFrom(y => y.LastModifiedById != null? y.LastModifiedBy.FullName : null));