stephen776
stephen776

Reputation: 9234

Using AutoMapper to map LINQ Query results to ViewModel Objects

First some background..I am using the Telerik MVC Grid to display data. The grid expects an IEnumerable to be passed into their GridModel class which I assume takes care of pages, sorting, filtering, etc.

To avoid circular refrences when passing this data as JSON via ajax I need to map the results from my EF linq querys to View model objects...AutoMapper would be my method of choice for this, but the only solution involving AutoMapper I have come up with hurts perfomance very badly.

I have a repository that returns an IEnumerable of my view model type to my action method that is called by the grid..

public IEnumerable<ResultViewModel> Search()
    {
        var person = _context.Persons;

         //this works and is the best performance wise but could be made simpler with automapper
        var result = person.Select(x => new ResultViewModel
                            {
                                FirstName = x.firstName,
                                LastName = x.lastName,
                                ///etc...
                            });

        //THIS IS SLOW but works
        //var result = Mapper.Map<IEnumerable<Person>, IEnumerable<ResultViewModel>>(person);

        //this does not work and errors at runtime
        //var result = person.Select(x => Mapper.Map<Person, ResultViewModel>(x));

        return result;

    }

Any ideas on how to keep my performance while using automapper to make things easier. I am assuming that the slow version using automapper is caused by the person collection being enumerated...then being parsed later on by the telerik grid

Upvotes: 3

Views: 4395

Answers (1)

John Farrell
John Farrell

Reputation: 24754

Sounds like you have an Select ( N + 1 ) issue where each item in the loop is loading related properties and therefore issuing another select query.

There shouldn't be any performance issues using automapper.

Try calling ToList() on person ( shouldn't it be people? ) before you do the automapping and breaking the IQueryable chain.

Upvotes: 1

Related Questions