2

Below are my classes

public class Student {
      public long Id { get; set; }
      public long? CollegeId { get; set; }
      public StudentPersonal StudentPersonal { get; set; }
    }   

    public class StudentPersonal {  
      public long? EthnicityId { get; set; }
      public bool? GenderId { get; set; }  // doesn't exist on UpdateModel, requires PropertyMap.SourceMember null check
    }   

    public class UpdateModel{
      public long Id { get; set; }
      public long? CollegeId { get; set; }
      public long? StudentPersonalEthnicityId { get; set; }
    }

Below is the AutoMapper config

Mapper.Initialize(a => {
    a.RecognizePrefixes("StudentPersonal");
}

Mapper.CreateMap<UpdateModel, StudentPersonal>()
    .ForAllMembers(opt => opt.Condition(src => src.PropertyMap.SourceMember != null && src.SourceValue != null));
Mapper.CreateMap<UpdateModel, Student>()
    .ForMember(dest => dest.StudentPersonal, opt => opt.MapFrom(src => Mapper.Map<StudentPersonal>(src)))                                
    .ForAllMembers(opt => opt.Condition(src => src.PropertyMap.SourceMember != null && src.SourceValue != null));

And the sample test case:

var updateModel = new StudentSignupUpdateModel();
updateModel.Id = 123;
updateModel.CollegeId = 456;
updateModel.StudentPersonalEthnicityId = 5;

var existingStudent = new Student();
existingStudent.Id = 123;
existingStudent.CollegeId = 777; // this gets updated
existingStudent.StudentPersonal = new StudentPersonal();
existingStudent.StudentPersonal.EthnicityId = null; // this stays null but shouldn't

Mapper.Map(updateModel, existingStudent);
Assert.AreEqual(777, existingStudent.CollegeId);  // passes
Assert.AreEqual(5, existingStudent.StudentPersonal.EthnicityId);  // does not pass

Has anyone gotten conditional mapping to work with prefixes? It works ok on the non prefixed object.

Adam Levitt
  • 10,316
  • 26
  • 84
  • 145

1 Answers1

0

The lambda you're passing to opts.Condition is too restrictive:

src => src.PropertyMap.SourceMember != null && src.SourceValue != null

In this property's case, src.PropertyMap is null every time (which you might expect, since there's no single property that maps to the destination nested property from the source object).

If you remove the PropertyMap.SourceMember check, your tests will pass. I'm not sure what impact this will have on the rest of your mapping though.

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
  • Thanks for the reply. The issue here is that there are fields on the destination side that don't exist on the source side, which caused an issue for me. I edited the original example to illustrate. Thoughts? – Adam Levitt Sep 15 '14 at 20:03