0

I'm modelling a 3rd party database using Automapper 8 and EF 6. One of my DTO classes needs to use a Where clause on an association to locate the correct record.

// Community table is mapped and working.
// Mapping breaks when mapping dest.Subjects
cfg.CreateMap<Person, PersonDto>()
    // snip many mappings
    .ForMember(dest => dest.Id,       act => act.MapFrom(src => src.ID))
    .ForMember(dest => dest.UserName, act => act.MapFrom(src => src.Community.NetworkLogin))
    .ForMember(
        dest => dest.Subjects,
        act => act.MapFrom(
            src => src.Community.StudentClasses.Where(
                subject => subject.Year == CurrentSemester.Year && subject.Semester == CurrentSemester.Semester)))
    .ForMember(
        dest => dest.Contacts,
        act => act.MapFrom(
            src => src.Community.Contacts.Where(
                contact => Contact.UseThis).Select(contact => contact.ContactDetails)));

This code works in production, but I'd really like to Unit Test this model. Running a simple test (get all records in the Mock) I'm hit with a NullReferenceException when it tries to access the Community.StudentClasses object.

I found this answer relating to NullReferenceExceptionexceptions and AutoMapper, which helped me fix the rest of the references in this config, but I'm still having issues with this one. The test works when I remove the Community.StudentClasses mapping.

I'm mocking objects using code similar to:

public static Person Person19788 =>
    new SchoolContact
    {
        ID                                      = 19788,
        NetworkLogin                            = "username",
        // Tried various creation methods
        // StudentClasses  = new List<StudentClass> {new StudentClass()},
        // StudentClasses = new List<StudentClass> {new StudentClass {Year = 0, Semester = 0}},
        StudentClasses = null,
        StudentContacts = null,
        Address         = Address19788
    };

CurrentSemester has been checked, and returns valid non-zero values for Year and Semester.

The strange thing is that the Contacts mapping works fine, even with null values. So I assume that I've broken my Subjects mapping somewhere along the line, but I'm unsure where else to look.

The Joker
  • 403
  • 7
  • 15

1 Answers1

0

It turns out that the problem was with my Subjects mapping after all. The top-level associations were mapped correctly, however the lower-level associations were not. (I didn't include these mappings because a) I didn't think about them, and b) there's only so much code that anyone would be willing to wade through).

After fixing up the w > x > y > z mappings everything is working as expected. I thought I'd exhausted all options before posting this question. Lesson learned: don't post to SO until you've slept on it and taken a fresh look at the code the next day.

The Joker
  • 403
  • 7
  • 15