Asp.net-Mvc-3

映射 ViewModel 後如何讓 AutoMapper 呼叫方法

  • May 10, 2020

映射源和目標後是否可以讓 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循環。這可能嗎?

我想你可以.AfterMap在這裡使用

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

引用自:https://stackoverflow.com/questions/6882826