Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 列表中的自动映射int属性值<;类型>;列出<;int>;_C#_Automapper - Fatal编程技术网

C# 列表中的自动映射int属性值<;类型>;列出<;int>;

C# 列表中的自动映射int属性值<;类型>;列出<;int>;,c#,automapper,C#,Automapper,我需要将int属性从对象列表映射到列表。 下面是我的班级结构: 我有一个父类: public class Parent { ... public List<Location> Locations { get; set; } } 映射的目标类: public class Destination { ... public List<int> Locations { get; set; } } 公共类目的地 { ... 公共列表位置{get;

我需要将int属性从对象列表映射到
列表
。 下面是我的班级结构:

我有一个父类:

public class Parent
{
    ...
    public List<Location> Locations { get; set; }
}
映射的目标类:

public class Destination
{
    ...
    public List<int> Locations { get; set; }
}
公共类目的地
{
...
公共列表位置{get;set;}
}
下面是我试图用来完成
List
List
之间映射的代码:

CreateMap()
.ForMember(d=>d.Locations,o=>o.MapFrom(s=>s.Locations.Select(l=>l.LocationId)))
这不管用。我得到以下错误:

AutoMapper.AutoMappingException:无法从Location.LocationId创建映射表达式 (System.Collections.Generic.IEnumerable`1[System.Int32])Destination.Locations(System.Collections.Generic.List`1[System.Int32])

知道我做得不对吗?

例外情况是:

AutoMapper.AutoMappingException:无法从Location.LocationId(System.Collections.Generic.IEnumerable1[System.Int32])到Destination.Locations(System.Collections.Generic.List1[System.Int32])创建映射表达式

我相信这是因为您试图将IEnumerable映射到列表。 您可以在
选择之后向映射表达式添加
ToList()
。(不推荐)
或者将
Locations
属性声明为目标类中的
IEnumerable

您需要更改AutoMapper配置,以在
Location
int
之间进行映射,然后它会为您处理其余部分:

cfg.CreateMap<Location, int>().ConvertUsing(source => source.LocationId);
cfg.CreateMap<Parent, Destination>().ForMember(dest => dest.Locations, opts => opts.MapFrom(src => src.Locations));
cfg.CreateMap().ConvertUsing(source=>source.LocationId);
CreateMap().formMember(dest=>dest.Locations,opts=>opts.MapFrom(src=>src.Locations));

有关工作示例,请参见。

您是否尝试过在select的末尾添加.ToList()?好主意。我试过这个,它似乎已经处理好了。谢谢这就是JamesT在上述评论中提出的建议。这解决了我的问题。谢谢正如Chris Pickford在下面建议的那样,我还必须添加位置到int的映射。这加上.ToList()解决了我的问题。@downvoter-想解释一下这个答案是如何不正确或可以改进的吗?不知道为什么你会投反对票。我不得不用你的第一行代码来得到正确的答案。
CreateMap<Parent, Destination>()
.ForMember(d => d.Locations, o => o.MapFrom(s => s.Locations.Select(l => l.LocationId)))
cfg.CreateMap<Location, int>().ConvertUsing(source => source.LocationId);
cfg.CreateMap<Parent, Destination>().ForMember(dest => dest.Locations, opts => opts.MapFrom(src => src.Locations));