Linq查询生成超时

时间:2016-04-11 15:34:40

标签: c# linq linq-to-sql

我有一个如下所示的查询:

var TheDataToDelete = (from x in MyDC.SomeTable
                       where x.....
                       select x).ToList();

if (TheDataToDelete.Count > 0)
{
  MyDC.SomeTable.DeleteAllOnSubmit(TheDataToDelete);
  MyDC.SubmitChanges();
}

有大约10K行要删除,在我的错误日志中,我有时(每周一次)看到这个错误:

Inner Exception Type: System.ComponentModel.Win32Exception
Inner Exception: The wait operation timed out
Inner Source: 
Exception Type: System.Data.SqlClient.SqlException
Exception: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.

我的代码出了什么问题,我需要修改什么才能修复它?

1 个答案:

答案 0 :(得分:6)

正如@Shyju建议的那样,使用Any()。但是也要删除ToList(),因为它已经执行了查询。不添加它将使查询具有延迟执行。而且因为那时只进行Any()查询会更有效率。

var TheDataToDelete = (from x in MyDC.SomeTable
                       where x.....
                       select x);

if (TheDataToDelete.AnY())
{
    MyDC.SomeTable.DeleteAllOnSubmit(TheDataToDelete);
    MyDC.SubmitChanges();
}

哪个会产生SQL查询;

SELECT
    (CASE
        WHEN EXISTS(
            SELECT x 
            FROM MyDC.SomeTable
            WHERE x
            ) THEN 1
        ELSE 0
     END) AS [value]

这是快速有效的。