2011-07-30 47 views
12

在映射源和目標之後讓AutoMapper調用方法是否可行?如何使AutoMapper在映射ViewModel之後調用方法

我的視圖模型是這樣的:

public class ShowCategoriesViewModel 
{ 
    public int category_id { get; set; } 
    public string category_name { get; set; } 

    public List<MvcApplication3.Models.Category> SubCategories { get; set; } 

    public void Sort() 
    { 
     SubCategories.Sort(new CompareCategory()); 
    } 

} 

我的控制器看起來像這樣:

 public ActionResult Index() 
    { 
     var category = db.Category.Where(y => y.parrent_id == null).ToList(); 

     Mapper.CreateMap<Category, ShowCategoriesViewModel>(). 
      ForMember(dest => dest.SubCategories, opt => opt.MapFrom(origin => origin.Category1)); 

     List<ShowCategoriesViewModel> scvm = Mapper.Map<List<Category>, List<ShowCategoriesViewModel>>(category); 

     foreach (ShowCategoriesViewModel model in scvm) 
     { 
      model.Sort(); 
     } 

     return View(scvm); 
    } 

我想有AutoMapper調用sort()方法,而不是做一個foreach循環。這可能嗎?

回答

18

我認爲你可以使用.AfterMap這裏

Mapper.CreateMap<Category, ShowCategoriesViewModel>() 
    .ForMember(dest => dest.SubCategories, opt => opt.MapFrom(origin => origin.Category1)) 
    .AfterMap((c,s) => s.Sort()); 
相關問題