Auto Mapper C#..将数据添加到mapper

时间:2018-05-14 14:43:33

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

 var config = new MapperConfiguration(cfg => {
    cfg.CreateMap<EmployeeSkill, EmployeeSkillDTO>(); 
 });

IMapper mapper = config.CreateMapper();

List<EmployeeSkill> ski = context.EmployeeSkill.Where(r => !r.IsDeleted && r.EmployeeID == employeeID).ToList();
List<EmployeeSkillDTO> mapObj = mapper.Map<List<EmployeeSkill>, List<EmployeeSkillDTO>>(ski);

return mapObj;

它返回

[
   {
    "SkillID": 1,
    "EmployeeID": 83,
    "YearOfExperience": 8,
    "Major": "major",
    "SkillName": null,
    "IsDeleted": false,
    "CreatedBY": 29,
    "CreationTime": "2018-05-14T15:53:06.203",
    "UpdatedBy": null,
    "UpdateTime": null
},

我需要从Skills表中返回SkillName ...我试过:

var config = new MapperConfiguration(cfg => {
    cfg.CreateMap<EmployeeSkill, EmployeeSkillDTO>().ForMember(x => x.SkillName, opt => opt.ResolveUsing(src => src.Skill.SkillName)) 
 });

但它不起作用..任何建议

1 个答案:

答案 0 :(得分:0)

你需要做两件事之一

  1. 停止在查询结果中使用.ToList(),并在配置中使用ProjectTo()opt.Map代替'opt.ResolveUsing`。 (优选的)。
  2. 检索EmployeeSkill并包含SkillName表时调用Include。 (这将获得您不需要的额外数据。)
  3. 方法#1:

    var ski = context.EmployeeSkill.Where(r => !r.IsDeleted && r.EmployeeID == employeeID);
    var mapObj = ski.ProjectTo<EmployeeSkillDTO>();
    

    方法#1配置

    cfg.CreateMap<EmployeeSkill, EmployeeSkillDTO>()
       .ForMember(x => x.SkillName, opt => opt.MapFrom(src => src.Skill.SkillName));
    

    方法#2:

    var ski = context.EmployeeSkill.Include(x => x.Skill)
        .Where(r => !r.IsDeleted && r.EmployeeID == employeeID).ToList();