[英]AutoMapper Conditional Mapping Not Working With Skipping Null Destination Values
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 下面是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));
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.
它可以在无前缀对象上正常运行。
The lambda you're passing to opts.Condition
is too restrictive: 您传递给
opts.Condition
的lambda opts.Condition
太严格了:
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). 在此属性的情况下,
src.PropertyMap
每次都为null
(您可能会期望,因为没有单个属性映射到源对象的目标嵌套属性)。
If you remove the PropertyMap.SourceMember
check, your tests will pass. 如果删除
PropertyMap.SourceMember
检查,则测试将通过。 I'm not sure what impact this will have on the rest of your mapping though. 我不确定这会对您的其余映射产生什么影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.