Amir Jalali
Amir Jalali

Reputation: 3212

Automapper and lazy loading with EF and performance

I have a model like this

public class Exam
{
    public int NewsId { get; set; }
    public string Title { get; set; }
    public string Description{ get; set; }
    public string Program{ get; set; }
 }

and a view model like this

public class ExamViewModel
{
    public int NewsId { get; set; }
    public string Title { get; set; }
}

and I do config Automapper like this

AutoMapper.Mapper.CreateMap<Exam, ExamViewModel>();

and in an ActionResult I used Automapper like this:

    public ActionResult Exam()
    {
        var examsDb = db.Exams;
        IEnumerable<ExamViewModel> examViewModel = AutoMapper.Mapper.Map<IEnumerable<Exam>, IEnumerable<ExamViewModel>>(examsDb);

        return View(examViewModel);
    }

and in view I loop through it

     @model IEnumerable<AraParsESOL.ViewModels.ExamViewModel>
       <ul>
      @foreach (var e in Model)
        { 
           <li>
              @Html.ActionLink(e.Title, "Type", "Exam")
            </li>
          }
      </ul>

My problem is that: As you can see in the Model There are 4 properties but in viewModel there are only 2 properties.

How can i get only those 2 properties in viewModel and not the entire Model?

What happens here is that in view after each loop it goes and get the required column from the database but i want only those 2 properties and not going back to database.

i can get the database like this db.Exam.ToList(); but it will cause the entire database gets back. i want to use best practices here?

i know i can get the data from database by anonymouse type and select command but then what is the use of automapper? what is the best solution here?

Upvotes: 3

Views: 2320

Answers (1)

Craig Stuntz
Craig Stuntz

Reputation: 126547

Don't use AutoMapper. It's not appropriate for IQueryable<T>. Instead, use LINQ projections:

public ActionResult Exam()
{
    var examsDb = db.Exams;
    IEnumerable<ExamViewModel> examViewModel = 
        from e in db.Exams
        select new ExamViewModel
        {
            NewsId = e.NewsId,
            Title = e.Title
        };

    return View(examViewModel);
}

If you look at the generated SQL, you will see that only the NewsId and Title columns are retured. It looks like the AutoMapper folks were interested in addressing this shortcoming, but I haven't heard anything about it since this.

Upvotes: 3

Related Questions