c# - AutoMapper 条件映射不适用于跳过空目标值

标签 c# mapping automapper prefixes

下面是我的类(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/

相关文章:

python - 是否可以映射数据并制作向量矩阵?

java - 可配置(例如 XML)Java Bean 到 Bean 映射框架

c# - 如何修复 Automapper 将连接表映射到 ViewModel

c# - 什么是等效于 SQL "in"语句的 lambda?

C# 阻止控制台窗口显示半秒?

c# - 在 C# 中实现状态机的最佳方式(当性能很重要时)是什么?

c# - Fluent NHibernate 映射 IList<Point> 作为单列的值

python - Pandas :当字典中有多个键时,通过映射添加列

c# - AutoMapper - 类型的条件映射

generics - 使用 AutoMapper 实现 .ToViewModel()