2

下面是我的课

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; }
    }

下面是 AutoMapper 配置

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));

以及示例测试用例:

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

有没有人得到条件映射来处理前缀?它适用于非前缀对象。

4

1 回答 1

0

您传递给的 lambdaopts.Condition限制性太强:

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

在此属性的情况下,src.PropertyMapnull每次(您可能会期望,因为没有单个属性可以从源对象映射到目标嵌套属性)。

如果您删除PropertyMap.SourceMember检查,您的测试将通过。不过,我不确定这会对您的其余映射产生什么影响。

于 2014-09-15T15:47:11.323 回答