【发布时间】: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#