使用Linq to SQL确定行是否存在的最快方法是什么? [英] What is the fastest way to determine if a row exists using Linq to SQL?

查看:70
本文介绍了使用Linq to SQL确定行是否存在的最快方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对一行的内容不感兴趣,我只想知道一行是否存在. Name列是主键,因此将有0或1个匹配的行.目前,我正在使用:

if ((from u in dc.Users where u.Name == name select u).Count() > 0)
    // row exists
else
    // row doesn't exist

尽管上述方法有效,但通过选择该行的所有内容(如果存在),它做了很多不必要的工作.以下内容是否会创建更快的查询:

if (dc.Users.Where(u => u.Name == name).Any())

...还是有更快的查询?

Count()方法可能会做额外的工作,因为(在TSQL中)EXISTSTOP 1通常更快.数据库可以优化至少有一行".就个人而言,我将使用any/predicate重载:

if (dc.Users.Any(u => u.Name == name)) {...}

当然,您可以通过观察TSQL来比较每个人的工作:

dc.Log = Console.Out;

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?

解决方案

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)) {...}

Of course, you can compare what each one does by watching the TSQL:

dc.Log = Console.Out;

这篇关于使用Linq to SQL确定行是否存在的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆