在映射源和目标之后,是否可以让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循环。这可能吗?
答案 0 :(得分:20)
我认为你可以在这里使用.AfterMap
Mapper.CreateMap<Category, ShowCategoriesViewModel>()
.ForMember(dest => dest.SubCategories, opt => opt.MapFrom(origin => origin.Category1))
.AfterMap((c,s) => s.Sort());