简体   繁体   中英

AutoMapper, Entity Framework and Counts

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.

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM