LINQ to Entity 查询优化
我目前有以下逻辑,构建 4 个整数的列表,其中每个整数代表某个项目 ID(1、2、3 或 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));
}
这非常有效,但我质疑效率此类查询,因为这似乎实际上生成并执行 4 个单独的查询。理想情况下,我想要一个有效的查询,返回 4 个总和。
有什么想法吗?
提前致谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将逻辑包装到一个查询中
(此代码未经测试,可能偏离基础,但只是抛出一个想法)
You could wrap your logic into one query
(This code is untested and could be way off base but just throwing out an idea)
在 LINQ 中,.Count() 方法强制执行查询。如果您需要 4 个不同的总计,则没有其他方法可以在一个语句中生成该总计。
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.