使用自动映射器将集合的属性映射到基元数组 [英] Using Automapper to map a property of a collection to an array of primitives
本文介绍了使用自动映射器将集合的属性映射到基元数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出以下几类:
class Parent
{
string Name { get; set; }
List<Child> children { get; set; }
}
class Child
{
short ChildId { get; set; }
string Name { get; set; }
}
class ParentViewModel
{
string Name { get; set; }
short[] ChildIds { get; set; }
}
当我打电话
Mapper.Map<Parent, ParentViewModel>(vm);
是否可以使AutoMapper将Child.ChildId
的列表转换为ParentViewModel.ChildIds
?
Is it possible to get AutoMapper to translate the list of Child.ChildId
to ParentViewModel.ChildIds
?
我试图做这样的事情:
Mapper.CreateMap<Child, short>()
.FromMember(dest => dest, opt => opt.MapFrom(src => src.ChildId));
Mapper.CreateMap<Parent, ParentViewModel>()
.FromMember(dest => dest.ChildIds, opt => opt.MapFrom(src => new[] {src.children}));
但是我收到一条错误消息,说它不知道如何将Child对象列表转换为int16.有什么建议吗?
But I get an error saying it doesn't know how to convert a list of Child objects to an int16. Any suggestions?
推荐答案
使用LINQ查询仅获取ChildId:
Use a LINQ query to grab just the ChildIds:
.ForMember(d => d.ChildIds, o => o.MapFrom(s => s.Children.Select(c => c.ChildId).ToArray()));
这篇关于使用自动映射器将集合的属性映射到基元数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文