【问题标题】:how to use a foreach loop in AutoMapper如何在 AutoMapper 中使用 foreach 循环
【发布时间】:2019-05-17 17:02:05
【问题描述】:

我发现使用 AutoMapper 从我的数据源映射到目的地很困难。我有一个包含对象列表的源类。现在我想使用 foreach 将该列表映射到单个类以迭代抛出列表,以便使用 Automapper 填充该类。

public class Source
{
  public List<StudentName> studentName {get; set;} 
}
public class StudentName
{
   public string Name { get; set;}
}

public class Destination
{
  public string FirstName { get; set;} 
}


 public List<Destination> GetStud(Source source)
 {               
     MapperConfigurationExpression cfg = new MapperConfigurationExpression();
     cfg.ValidateInlineMaps = false;
     cfg.CreateMap<Source,  Destination>();
     MapperConfiguration mapperConfig = new MapperConfiguration(cfg);
     IMapper mapper = new Mapper(mapperConfig);


     var viewModel= new List<Destination>();

     // enter code here
     foreach (var item in source.studentName)
     {
         var destination = new Destination();    
         destination.FirstName = item.Name;                   

         destination = mapper.Map<Destination>(item);

         viewModel.Add(destination);

         var man = 0;
     }

     return viewModel;

}

我尝试过的这种方法给了我以下错误 未映射的成员被发现。查看下面的类型和成员。 添加自定义映射表达式、忽略、添加自定义解析器或修改源/目标类型 对于没有匹配的构造函数,添加一个无参数 ctor、添加可选参数或映射所有构造函数参数

【问题讨论】:

  • 源类和目标类完全不同。您必须指明要映射的属性的对应关系。

标签: c#


【解决方案1】:

您必须分配要映射的属性。不需要做foreach,做映射到List:

public List<Destination> GetStud(Source source)
{  
    MapperConfigurationExpression cfg = new MapperConfigurationExpression();
    cfg.ValidateInlineMaps = false;
    cfg.CreateMap<StudentName,  Destination>()
       .ForMember(a=> a.FirstName, opt => opt.MapFrom(itm=> itm.Name));

    MapperConfiguration mapperConfig = new MapperConfiguration(cfg);
    IMapper mapper = new Mapper(mapperConfig);      

    var viewModel = mapper.Map<List<Destination>>(source.studentName);

    return viewModel;
}

【讨论】:

  • 你能详细说明什么是 src
  • 嗨@Seth,src 是你的源变量。我修改了代码;)
猜你喜欢
  • 1970-01-01
  • 2015-07-04
  • 2019-11-21
  • 2023-03-27
  • 2015-05-04
  • 2019-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多