1

我一直认为存在查询的 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 以查找集合中是否存在任何重复项。我无法理解的是,为什么简单的 Any 子句上的 LINQ to SQL 会超时。任何解释在这里都会非常棒。

编辑

来自 LINQ Pad ANY 的 SQL

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])
                    )
                )
            )
        )
4

1 回答 1

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");
于 2013-06-04T07:16:58.263 回答