AutoMapper将来自ViewModel的int []或List <int>映射到域模型中的List <Type>

1 c# mapping asp.net-mvc viewmodel automapper

我是AutoMapper的新手,我一直在阅读和阅读这里的问题,但我无法弄清楚什么看起来像一个非常微不足道的问题.

首先是我的课程,然后是问题:

GatewayModel.cs

public class Gateway
{
    public int GatewayID { get; set; }
    public List<Category> Categories { get; set; }
    public ContentType ContentType { get; set; }

    // ...
}

public class Category
{
    public int ID { get; set; }
    public int Name { get; set; }

    public Category() { }
    public Category( int id ) { ID = id; }
    public Category( int id, string name ) { ID = id; Name = name; } 
}

public class ContentType
{
    public int ID { get; set; }
    public int Name { get; set; }

    public ContentType() { }
    public ContentType( int id ) { ID = id; }
    public ContentType( int id, string name ) { ID = id; Name = name; } 
}
Run Code Online (Sandbox Code Playgroud)

GatewayViewModel.cs

public class GatewayViewModel
{
    public int GatewayID { get; set; }
    public int ContentTypeID { get; set; }
    public int[] CategoryID { get; set; }
    // or public List<int> CategoryID { get; set; }
    // ...
}
Run Code Online (Sandbox Code Playgroud)

从我一整天都在阅读的内容来看,这是我迄今为止所想到的.我不知道如何将View [](或List,如果需要)从ViewModel映射到Model中的List.

的Global.asax.cs

Mapper.CreateMap<Gateway, GatewayViewModel>();
Mapper.CreateMap<GatewayViewModel, Gateway>()
    .ForMember( dest => dest.ContentType, opt => opt.MapFrom( src => new ContentType( src.ContentTypeID ) ) )
    .ForMember( /* NO IDEA ;) */ );
Run Code Online (Sandbox Code Playgroud)

基本上我需要将ViewModel中的所有int [] CategoryID项映射到Model中List Categories类型的ID属性.对于反向映射,我需要将所有ID从Category类型映射到我的int [](或List)CategoryID,但我想我已经想到了(还没有到达那里).如果我需要为反向映射做类似的事情,请告诉我.

仅供参考,我的ViewModel中的int [] CategoryID被绑定到我视图中的SelectList.

我希望AutoMapper的CodePlex项目站点有一个更完整的文档,但我很高兴他们至少拥有他们拥有的东西.

谢谢!

Dar*_*rov 5

您可以执行以下操作:

Mapper
    .CreateMap<int, Category>()
    .ForMember(
        dest => dest.ID, 
        opt => opt.MapFrom(src => src)
);

Mapper
    .CreateMap<GatewayViewModel, Gateway>()
    .ForMember(
        dest => dest.Categories, 
        opt => opt.MapFrom(src => src.CategoryID)
);

var source = new GatewayViewModel
{
    CategoryID = new[] { 1, 2, 3 }
};

Gateway dst = Mapper.Map<GatewayViewModel, Gateway>(source);
Run Code Online (Sandbox Code Playgroud)

显然,您无法将Name属性从视图模型映射到模型,因为它不存在.