2011-07-30 6 views
12

Có phải nó có thể làm cho AutoMapper gọi một phương thức sau khi ánh xạ nguồn và đích?Làm thế nào để làm cho AutoMapper gọi một phương thức sau khi ánh xạ một ViewModel

My ViewModel trông như thế này:

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

} 

Và điều khiển của tôi trông như thế này:

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

Tôi muốn có AutoMapper gọi phương thức Sort(), thay vì thực hiện một vòng lặp foreach . Điều này có thể không?

Trả lời

18

Tôi nghĩ rằng bạn có thể sử dụng .AfterMap đây

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