2011-06-16 22 views
1

我是新來的AutoMapper,我一直在閱讀和閱讀周圍的問題,但我不能弄清楚看起來像什麼一個非常微不足道的問題。AutoMapper映射int []或列表<int>從ViewModel到列表<Type>在領域模型

首先我的班,那麼問題(S):

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

基本上我需要映射所有INT []從視圖模型類別ID項列表關鍵字在模型類型的ID屬性格式。對於反向映射,我需要將所有ID從類別類型映射到我的int [](或List)CategoryID,但我想我已經找到了(尚未得到)。如果我需要爲反向映射做類似的事情,請告訴我。

僅供參考,我的int []我的ViewModel中的CategoryID綁定到我的View中的SelectList。

我希望AutoMapper的CodePlex項目網站有更完整的文檔,但我很高興他們至少擁有他們擁有的東西。

謝謝!

回答

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

顯然,你不能從視圖模型Name屬性,因爲它不存在映射到模型。

相關問題