自动映射器 - 在映射之前编辑对象

时间:2018-05-14 09:37:29

标签: c# asp.net-web-api automapper

我有EmployeeSkillDTO类型的技能对象,我想使用自动映射器,但我想设置CreationTime = DateTime.Now,但请注意技能对象有creationTime = null

EmployeeSkillController:

EmployeeSkill ski = context.EmployeeSkill.Where(r => r.SkillID == skill.SkillID && r.EmployeeID == skill.EmployeeID).FirstOrDefault();

if (ski == null){
   Mapper.Initialize(cfg =>{
      cfg.CreateMap<EmployeeSkillDTO, EmployeeSkill>();
   });

   var map = Mapper.Map<EmployeeSkillDTO, EmployeeSkill>(skill);

   //ski = new EmployeeSkill
   //{
   //    SkillID = skill.SkillID,
   //    EmployeeID = skill.EmployeeID,
   //    Major = skill.Major,
   //    YearOfExperience = skill.YearOfExperience,
   //    CreatedBY = skill.CreatedBY,
   //    CreationTime = DateTime.Now,
   //};
context.EmployeeSkill.Add(map);

使用自动映射器之前的注释部分.....

1 个答案:

答案 0 :(得分:3)

这样的东西
cfg.CreateMap<EmployeeSkillDTO, EmployeeSkill>()
   .ForMember(x => x.CreationTime, opt => opt.ResolveUsing(src => DateTime.Now));

可能有用吗?