2011-07-30 49 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()); 
相关问题