简体   繁体   中英

LINQ to Entity query optimization

I currently have the following logic that builds a list of 4 integers, where each integer represents a sum of all votes for a certain item ID (1, 2, 3 or 4):

List<int> totals = new List<int>();

using (RepositoryEntities entityContext = new RepositoryEntities())
{
    totals.Add(entityContext.ItemVotes.Count(v => v.Vote == 1));
    totals.Add(entityContext.ItemVotes.Count(v => v.Vote == 2));
    totals.Add(entityContext.ItemVotes.Count(v => v.Vote == 3));
    totals.Add(entityContext.ItemVotes.Count(v => v.Vote == 4));
}

This works very well, but I'm questioning the efficiency of such querying, because this seems to actually generate and execute 4 separate queries. Ideally I'd want to have a single, efficient query that returns me the 4 sums.

Any ideas?
Thanks in advance.

You could wrap your logic into one query

totals.AddRange(entityContext.ItemVotes
    .Where(iv => iv.Vote >= 1 && iv.Vote <= 4)
    .GroupBy(iv => iv.Vote)
    .OrderBy(grp => grp.Key)
    .Select(grp => grp.Count());

(This code is untested and could be way off base but just throwing out an idea)

in LINQ the .Count() method forces execution of a query. If you need 4 different totals there is no other way to produce that in one statement.

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