Linq to Entities可以计算行数而无需返回行

Linq to Entities figure out count of rows without returning rows
2020-10-22
  •  译文(汉语)
  •  原文(英语)

我希望你们中的一个可以帮助我解决这个问题:给定以下方法,我可以使计数在DB Server上完成而不是检索所有行,并且该函数不应针对每个搜索名称运行查询,对于每个函数调用,它应该恰好运行1条SQL语句.Linq to Entities可以计算行数而无需返回行

速聊1:
键入代码通常是一个更好的主意,以便其他人可以复制它.要将文本格式化为代码,每行必须以四个空格开头.
解决过程1

您可以使用Contains转换为WHERE IN子句的方式来大大简化查询.然后只需计算匹配的行.

public static int CountEmployeesByName(IEnumerable<string> namesToSearch)
{
    using (var context = new ApplicationEntities())
    {
          return context.employees
                        .Where(e => namesToSearch.Contains(e.name))
                        .Count();
    }
}
速聊1:
对不起,我忘了说:问题的第一部分只需一行代码更改,第二部分仅一行代码更改,您能做到吗?
速聊2:
我不明白为什么会有限制.这完成了两件事-基本上将其转变为select count(*) from employees where name in (....)
速聊3:
不幸的是,这就是我的限制.我知道您的感受,我想知道同样的问题.
速聊4:
我想您可以使用LinqKit中的PredicateBuilder,但我看不到如何在少于3行的更改中做到这一点.我认为您至少需要更改的定义queries,每个名称的选择逻辑以及汇总已建立查询的语句.

I hope one of you guys can help me with this question: Given the method below, can I cause the count to be done on the DB Server rather than retrieve all the rows, and the function should not be running query for each search name, it should run exactly 1 SQL statement for each call of the function.Linq to Entities figure out count of rows without returning rows

Talk1:
It's usually a better idea to type in your code so others can copy it. To format text as code each line has to start with four spaces.
Solutions1

You can simplify your query dramatically by using Contains which will translated to a WHERE IN clause. Then simply count the matching rows.

public static int CountEmployeesByName(IEnumerable<string> namesToSearch)
{
    using (var context = new ApplicationEntities())
    {
          return context.employees
                        .Where(e => namesToSearch.Contains(e.name))
                        .Count();
    }
}
Talk1:
I'm sorry I forgot to say: can you do it with only 1 line of code change for the first part and one line of code change for the second part of the question?
Talk2:
I don't understand why there is a restriction. This does both things - basically turns it into select count(*) from employees where name in (....)
Talk3:
That is the restriction I was given unfortunately. I know how you feel, I wondered the same question.
Talk4:
I suppose you could use a PredicateBuilder from LinqKit but I don't see how you could do it in less than 3 line changes. At a minimum I think you'd need to change the definition of queries, the selection logic for each name, and the statement that sums the built up queries.
转载于:https://stackoverflow.com/questions/30552571/linq-to-entities-figure-out-count-of-rows-without-returning-rows

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入