Linq To Entities - Any VS First VS Exists

后端 未结 5 1184
滥情空心
滥情空心 2021-01-07 21:36

I am using Entity Framework and I need to check if a product with name = \"xyz\" exists ...

I think I can use Any(), Exists() or First().

Which one is the b

5条回答
  •  无人及你
    2021-01-07 22:01

    One would think Any() gives better results, because it translates to an EXISTS query... but EF is awfully broken, generating this (edited):

    SELECT 
    CASE WHEN ( EXISTS (SELECT 
        1 AS [C1]
        FROM [MyTable] AS [Extent1]
        WHERE Condition
    )) THEN cast(1 as bit) WHEN ( NOT EXISTS (SELECT 
        1 AS [C1]
        FROM [MyTable] AS [Extent2]
        WHERE Condition
    )) THEN cast(0 as bit) END AS [C1]
    FROM  ( SELECT 1 AS X ) AS [SingleRowTable1]
    

    Instead of:

    SELECT 
    CASE WHEN ( EXISTS (SELECT 
        1 AS [C1]
        FROM [MyTable] AS [Extent1]
        WHERE Condition
    )) THEN cast(1 as bit)
       ELSE cast(0 as bit) END AS [C1]
    FROM  ( SELECT 1 AS X ) AS [SingleRowTable1]
    

    ...basically doubling the query cost (for simple queries; it's even worse for complex ones)

    I've found using .Count(condition) > 0 is faster pretty much always (the cost is exactly the same as a properly-written EXISTS query)

提交回复
热议问题