AutoMapper映射int[]或List<;int>;从ViewModel到列表<;类型>;域模型中

本文关键字:int lt gt 列表 类型 模型 ViewModel 映射 List AutoMapper | 更新日期: 2023-09-27 17:59:12

我是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; } 
}

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; }
    // ...
}

从我一整天的阅读来看,这就是我到目前为止所了解到的。我不知道如何将int[](或者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 ;) */ );

基本上,我需要将ViewModel中的所有int[]CategoryID项映射到Model中List Categories类型的ID属性。对于反向映射,我需要将Category类型的所有ID映射到我的int[](或List)CategoryID,但我想我已经解决了这个问题(还没有实现)。如果我需要为反向映射做一些类似的事情,请告诉我。

仅供参考,ViewModel中的int[]CategoryID已绑定到视图中的SelectList。

我希望AutoMapper的CodePlex项目网站有一个更完整的文档,但我很高兴他们至少有他们所拥有的。

谢谢!

AutoMapper映射int[]或List<;int>;从ViewModel到列表<;类型>;域模型中

您可以执行以下操作:

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);

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