Is it possbile to make AutoMapper call a method after mapping source and destination?
My ViewModel looks like this:
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());
}
}
And my Controller looks like this:
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);
}
I would like to have AutoMapper call the Sort()
method, instead of doing a foreach
loop. Is this possible?
Inside this article, it discusses performance and it indicates that Automapper is 7 times slower than manual mapping. This test was done on 100,000 records and I must say I was shocked.
Polymorphic element types in collectionsAutoMapper supports polymorphic arrays and collections, such that derived source/destination types are used if found.
First install the NuGet Package Manager in your Visual Studio IDE. Once done, go to "Tools" -> "Library Packet Manager" -> "Packet manager Console". Press Enter. This will install AutoMapper and the next time you open MVC application in Visual Studio, it will automatically add a DLL reference to the project.
I think you can use .AfterMap
here
Mapper.CreateMap<Category, ShowCategoriesViewModel>()
.ForMember(dest => dest.SubCategories, opt => opt.MapFrom(origin => origin.Category1))
.AfterMap((c,s) => s.Sort());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With