Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make AutoMapper call a method after mapping a ViewModel

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?

like image 564
Nanek Avatar asked Jul 30 '11 11:07

Nanek


People also ask

Is AutoMapper faster than manual mapping?

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.

Can AutoMapper map collections?

Polymorphic element types in collectionsAutoMapper supports polymorphic arrays and collections, such that derived source/destination types are used if found.

How AutoMapper is implemented in MVC?

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.


Video Answer


1 Answers

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());
like image 74
David Fox Avatar answered Sep 22 '22 21:09

David Fox