Quantcast
Channel: Entity Framework
Viewing all articles
Browse latest Browse all 10318

Edited Issue: Query: Inefficient SQL generated for Any() [192]

$
0
0
Repro Steps:
1. Execute an Entity Framework query that uses Any() to check for the existence or absence of a matching record.
2. Check the executed SQL.

When using the Any() method on Entity Framework IQueryable, e.g.:

```
context.Users.Any(u => u.UserId == userId);

```
The generated T-SQL is as follows:

```
SELECT
CASE WHEN ( EXISTS (SELECT
1 AS [C1]
FROM [dbo].[Users] AS [Extent1]
WHERE [Extent1].[User_ID] = @p__linq__0
)) THEN cast(1 as bit) WHEN ( NOT EXISTS (SELECT
1 AS [C1]
FROM [dbo].[Users] AS [Extent2]
WHERE [Extent2].[User_ID] = @p__linq__0
)) THEN cast(0 as bit) END AS [C1]
FROM ( SELECT 1 AS X ) AS [SingleRowTable1]

```
There is no reason for the second WHEN query. Instead the query could be simplified to:

SELECT
CASE WHEN ( EXISTS (SELECT
1 AS [C1]
FROM [dbo].[Users] AS [Extent1]
WHERE [Extent1].[User_ID] = @p__linq__0
)) THEN cast(1 as bit) ELSE cast(0 as bit) END AS [C1]
FROM ( SELECT 1 AS X ) AS [SingleRowTable1]

In general, when projecting what would be a SQL predicate, we translate it into a case statement to account for SQL’s three-valued logic (true, false or null). However, as you have noticed, as EXISTS cannot return null, in this case this is redundant. We are tracking the issue on our side and have it in the backlog for future releases.

In the meantime, here are some possible ways to work around this issue and avoid duplication of the query:

var result = context.Users.Where(u => u.UserId == userId).Count() > 0;

The comparison to 0 in this case would occur on the client.

var query5 = context.CreateQuery<bool>(
"select true from {1} as b where EXISTS(select 1 from Model.Users as u where u.UserId == userId)"
).ToList().Count > 0;

In this case both the count and the comparison to 0 happen on the client."

This item was migrated from the DevDiv work item tracking system [ID=299943].

This work item originated from connect.microsoft.com. A member of the EF team at Microsoft should close the related Connect issue when closing this work item.

Viewing all articles
Browse latest Browse all 10318

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>