c# - 如何使用 Automapper 将集合映射到集合容器?

标签 c# automapper

我在尝试映射这两个类时遇到了一些问题(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/

相关文章:

c# - IIS 不识别 View 模型注释

C# AutoMapper - 继承映射 - 简单示例

c# - 必需属性不适用于外键下拉列表

c# - IISExpress 找不到使用 Visual Studio 2013 运行本地主机的 ssl 页面

c# - 自动映射 - 对于 IEnumerable 映射具有不同名称的多个属性

c# - 为什么每次引用源集合时,Automapper 都会将一个具体集合映射到一个新实例?

c# - 如何配置 Automapper 4 以允许空目标值

C# AutoMapper 映射多对多问题,外键错误

c# - 从 IIS 7/8 中的静态内容中删除服务器 header

c# - MVVM,对ViewModelLocator和DataTemplate感到困惑,导致ViewFirst vs ViewModel First