LinqToSql 中的标量函数
在 ADO.Net/SQLClient 中我经常会做这样的事情:
从 SomeTable WHERE SomeKey = 1234 中选择 COUNT(*)
...并使用executescalar 触发它以返回count 的值 - 用于简单检查是否存在某些内容。
我如何使用 LinqToSql 做同样的事情?
In ADO.Net/SQLClient I would often do something like this:
SELECT COUNT(*) FROM SomeTable WHERE SomeKey = 1234
...and fire it using executescalar to return the value of count - for a simple check if something exists.
How would I do the same using LinqToSql?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您还可以使用
Count()
。但这需要始终遍历所有行,而
Any()
可以在第一个匹配行之后返回 - 因此Any()
可能具有更好的性能。You could also use
Count()
.But this requires always to go through all rows while
Any()
can return after the first matching row - soAny()
might have better performance.请记住,Linq to Sql 是延迟执行,这意味着查询仅在您访问集合时才实际执行。 因此:
将在 SQL 方面变成 SELECT Count()。
Remember, Linq to Sql is deferred execution, which means, the query only actually executes when you access the collection. Therefore:
Will turn into a SELECT Count() on the SQL side of things.
如果您想查看某些内容是否存在,您可以使用 any 函数:
或者如果您实际上想知道计数,您可以使用 where 函数和 count 函数:
If you're looking to see if something exists you can use the any function:
or if you actually want to know that count you can use the where function and the count function: