Reputation: 4482
I'm trying to use AutoMapper to map my paged (https://www.nuget.org/packages/X.PagedList) collection of entities to my ViewModel. This is probably easier explained with code:
The Model:
public class Article {
public int Id { get; set; }
public string Title { get; set; }
// ...
public virtual ICollection<User> Subscribers { get; set; }
}
View Model:
public class ArticleViewModel {
public class ArticleListEntry {
public int Id { get; set; }
public string Title { get; set; }
// ...
public int SubscribersCount { get; set; }
}
// ...
public IPagedList<ArticleListEntry> ArticleList { get; set; }
}
Mapping Config:
CreateMap<Article, ArticleViewModel.ArticleListEntry>();
Controller:
public ActionResult Index(int? page) {
int pageSize = 25;
int pageNumber = (page ?? 1);
var model = new ArticleViewModel();
IQueryable<Article> articles = db.Articles.OrderBy(a => a.Title);
model.Articles = Mapper.Map<IPagedList<Article>, IPagedList<ArticleViewMode.ArticleListEntry>>(articles).ToPagedList(pageNumber, pageSize);
return View(model);
}
Now then, this works. But, as some will quickly point out, this does a new database call for each entry in the list when attempting to get the count of the Subscribers - so takes a good second or two if you have a large page size (and this is clearly wrong anyway). I can add in .Include(a => a.Subscribers)
when I grab the articles, but this pulls in a lot of unnecessary data (doesn't it?) when all I want is the count. Is there something obvious I am missing here?
If using AutoMapper here is completely stupid, please tell me off and advise me on what would be more sane.
Upvotes: 0
Views: 743
Reputation: 4482
Heh, this works and comes out with a really nice SQL statement too!
model.Articles = db.Articles.OrderBy(a => a.Title).ProjectTo<ArticleViewMode.ArticleListEntry>().ToPagedList(pageNumber, pageSize);
Fixed just after you commentsd but thanks anyway Charles Mager :)
Upvotes: 1