使用 Linq to SQL 确定行是否存在的最快方法是什么?
- 作者: 尘归尘土归土9836321
- 来源: 51数据库
- 2022-12-08
问题描述
我对一行的内容不感兴趣,我只想知道一行是否存在.Name 列是主键,因此将有 0 或 1 个匹配行.目前,我正在使用:
I am not interested in the contents of a row, I just want to know if a row exists. The Name column is a primary key, so there will either be 0 or 1 matching rows. Currently, I am using:
if ((from u in dc.Users where u.Name == name select u).Count() > 0)
// row exists
else
// row doesn't exist
虽然上述工作正常,但它通过选择行的所有内容(如果存在)做了很多不必要的工作.以下是否会创建更快的查询:
While the above works, it does a lot of unnecessary work by selecting all the contents of the row (if it exists). Does the following create a faster query:
if (dc.Users.Where(u => u.Name == name).Any())
...或者有更快的查询吗?
...or is there an even faster query?
推荐答案
Count() 方法可能会做额外的工作,如(在 TSQL 中)EXISTS 或 TOP 1 通常要快得多;数据库可以优化是否至少有一行".就个人而言,我会使用 any/predicate 重载:
The Count() approach may do extra work, as (in TSQL) EXISTS or TOP 1 are often much quicker; the db can optimise "is there at least one row". Personally, I would use the any/predicate overload:
if (dc.Users.Any(u => u.Name == name)) {...}
当然,您可以通过观看 TSQL 来比较每个人的行为:
Of course, you can compare what each one does by watching the TSQL:
dc.Log = Console.Out;
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
