我需要将int属性从对象列表映射到List< int>.
这是我的类结构:
我有一个家长班:
public class Parent
{
...
public List<Location> Locations { get; set; }
}
位置类别:
public class Location
{
public int LocationId { get; set; }
public string Name { get; set; }
}
映射的目标类:
public class Destination
{
...
public List<int> Locations { get; set; }
}
这是我尝试用来完成List< Location>与列出< int> ;:
CreateMap<Parent, Destination>()
.ForMember(d => d.Locations, o => o.MapFrom(s => s.Locations.Select(l => l.LocationId)))
这不起作用.我收到以下错误:
AutoMapper.AutoMapperMappingException: Unable to create a map expression from Location.LocationId
(System.Collections.Generic.IEnumerable`1[System.Int32]) to Destination.Locations (System.Collections.Generic.List`1[System.Int32])
知道我在做什么不对吗?
解决方法:
作为例外说明:
AutoMapper.AutoMapperMappingException: Unable to create a map expression from Location.LocationId (System.Collections.Generic.IEnumerable1[System.Int32]) to Destination.Locations (System.Collections.Generic.List1[System.Int32])
我相信发生这种情况是因为您试图将IEnumerable映射到列表.
您可以在Select之后将ToList()添加到地图表达式中. (不建议)
或将Locations属性声明为IEnumerable< int>.在您的Destination类中.