下面是我的类(class)
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
有没有人得到条件映射来处理前缀?它在非前缀对象上工作正常。
最佳答案
您传递给 opts.Condition
的 lambda 过于严格:
src => src.PropertyMap.SourceMember != null && src.SourceValue != null
在此属性的情况下,src.PropertyMap
每次都是 null
(您可能会预料到,因为没有单个属性从源映射到目标嵌套属性对象)。
如果您删除 PropertyMap.SourceMember
检查,您的测试将通过。不过,我不确定这会对您的其余映射产生什么影响。
关于c# - AutoMapper 条件映射不适用于跳过空目标值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25839119/