LINQ中的任何vs Where子句

时间:2013-05-29 16:41:55

标签: linq linq-to-sql

我一直认为LINQ to SQL等效于存在的查询是使用Any()。但我最近在LINQ中编写了一个查询,它基本上试图找出单个表中是否存在重复记录。

任何context.Contacts.Any(c => ((c.FirstName == contact.FirstName && c.LastName == contact.LastName && c.AddressLine1 == contact.AddressLine1 && c.Zip == contact.Zip)|| (!String.IsNullOrEmpty(contact.Email) && c.Email == contact.Email)))

匹配条件很容易找到具有相同FirstName,LastName和AddressLine1或相同电子邮件的联系人。此查询在30秒内超时(默认),此表中只有500K行。

其中context.Contacts.Where(c => ((c.FirstName == contact.FirstName && c.LastName == contact.LastName && c.AddressLine1 == contact.AddressLine1 && c.Zip == contact.Zip)|| (!String.IsNullOrEmpty(contact.Email) && c.Email == contact.Email))).Count()>0

我被迫使用Where子句然后计数大于0来查找集合中是否存在任何重复。我无法理解的是,为什么LINQ to SQL on simple Any子句超时。 任何解释都会非常好。

修改

来自LINQ Pad的SQL ANY

SELECT 
(CASE 
    WHEN EXISTS(
        SELECT NULL AS [EMPTY]
        FROM [Accounts].[Contacts] AS [t0]
        WHERE ([t0].[CompanyID] = @p0) AND ((([t0].[FirstName] = @p1) AND ([t0].[LastName] = @p2) AND ([t0].[AddressLine1] = @p3) AND ([t0].[Zip] = @p4)) OR (([t0].[FirstName] = @p5) AND ([t0].[LastName] = @p6) AND (EXISTS(
            SELECT NULL AS [EMPTY]
            FROM [Accounts].[PhoneNumbers] AS [t1]
            WHERE ([t1].[ContactNumber] = @p7) AND ([t1].[ContactID] = [t0].[ContactID])
            ))))
        ) THEN 1
    ELSE 0
 END) AS [value]

其中

SELECT [t0].[ContactID]
    ,[t0].[CompanyID]
    ,[t0].[CompanyTitle]
    ,[t0].[FirstName]
    ,[t0].[LastName]
    ,[t0].[AddressLine1]
    ,[t0].[AddressLine2]
    ,[t0].[City]
    ,[t0].[State]
    ,[t0].[Zip]
    ,[t0].[Email]
    ,[t0].[Salutation]
    ,[t0].[IsActive]
FROM [Accounts].[Contacts] AS [t0]
WHERE ([t0].[CompanyID] = @p0)
    AND (
        (
            ([t0].[FirstName] = @p1)
            AND ([t0].[LastName] = @p2)
            AND ([t0].[AddressLine1] = @p3)
            AND ([t0].[Zip] = @p4)
            )
        OR (
            ([t0].[FirstName] = @p5)
            AND ([t0].[LastName] = @p6)
            AND (
                EXISTS (
                    SELECT NULL AS [EMPTY]
                    FROM [Accounts].[PhoneNumbers] AS [t1]
                    WHERE ([t1].[ContactNumber] = @p7)
                        AND ([t1].[ContactID] = [t0].[ContactID])
                    )
                )
            )
        )

1 个答案:

答案 0 :(得分:0)

不完全确定这是否是你想要的,但你可以比较,我猜你不会经常运行测试,因为在将数据输入到数据库之前测试存在会更好。

如果您想找到重复项,那么

var queryA = from a in db.someTable
            select a.value;
foreach(var row in queryA){
Console.Write(queryA.Where(b => b == row).Count() > 1 ? row: "");
}

如果您只想测试它是否存在。

var queryA = from a in db.someTable
            select a.value;
var queryB = queryA;
queryB.Distinct();
Console.Write(queryB.Count() != queryA.Count() ? "Yes" : "No");