我在尝试映射这两个类时遇到了一些问题(Control -> ControlVM)
public class Control
{
public IEnumerable<FieldType> Fields { get; set; }
public class FieldType
{
//Some properties
}
}
public class ControlVM
{
public FieldList Fields { get; set; }
public class FieldList
{
public IEnumerable<FieldType> Items { get; set; }
}
public class FieldType
{
//Properties I'd like to map from the original
}
}
我试过 opt.ResolveUsing(src => new { Items = src.Fields })
但显然 AutoMapper 无法解析匿名类型。还尝试扩展 ValueResolver
, 但也没有用。
注意:此 VM 稍后会在 WebApi 中使用,并且 JSON.NET 需要一个围绕集合的包装器才能正确反序列化它。所以移除包装器不是解决方案。
注意2:我也在做Mapper.CreateMap<Control.FieldType, ControlVM.FieldType>()
, 所以问题不存在。
最佳答案
这对我有用:
Mapper.CreateMap<Control.FieldType, ControlVM.FieldType>();
// Map between IEnumerable<Control.FieldType> and ControlVM.FieldList:
Mapper.CreateMap<IEnumerable<Control.FieldType>, ControlVM.FieldList>()
.ForMember(dest => dest.Items, opt => opt.MapFrom(src => src));
Mapper.CreateMap<Control, ControlVM>();
更新:以下是如何以另一种方式映射:
Mapper.CreateMap<ControlVM.FieldType, Control.FieldType>();
Mapper.CreateMap<ControlVM, Control>()
.ForMember(dest => dest.Fields, opt => opt.MapFrom(src => src.Fields.Items));
关于c# - 如何使用 Automapper 将集合映射到集合容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10554814/