cool breeze
cool breeze

Reputation: 4811

How to do a where in subquery using Entity Framework?

I have a query like:

var result = from u in this.DataContext.Users
             join l in DataContext.Locations on u.Id equals l.userId
             where u.active == 1
             select u;

return result ;

I want to add a subquery WHERE IN clause like:

WHERE u.Id IN (SELECT userId FROM approved_users)

Is this possible?

Upvotes: 2

Views: 3998

Answers (1)

ninja coder
ninja coder

Reputation: 1117

I am not sure why you want it in a sub query, it seems simpler to just join the Approved Users table, but I do not know the requirement so I have presented two options. One option that has a sub query and one option with the additional join. I am also making an assumption that you don't have any navigation properties.

Option 1 - Subquery:

var subQuery =
    from u in context.Users.Where(x => context.ApprovedUsers.Select(y => y.ApprovedUserId).Contains(x.UserId))
    join l in context.Locations on u.UserId equals l.UserId
    where u.IsActive == true
    select u;

which generates something like this

SELECT 
    [Extent1].[UserId] AS [UserId], 
    [Extent1].[Name] AS [Name], 
    [Extent1].[IsActive] AS [IsActive]
FROM  [dbo].[User] AS [Extent1]
INNER JOIN [dbo].[Location] AS [Extent2] ON [Extent1].[UserId] = [Extent2].[UserId]
WHERE ( EXISTS (SELECT 
    1 AS [C1]
    FROM [dbo].[ApprovedUser] AS [Extent3]
    WHERE [Extent3].[ApprovedUserId] = [Extent1].[UserId]
)) AND (1 = [Extent1].[IsActive])

Option 2 - Additional Join:

var query =
    from u in context.Users
    join l in context.Locations on u.UserId equals l.UserId
    join au in context.ApprovedUsers on u.UserId equals au.ApprovedUserId
    where u.IsActive == true
    select u;

which generates:

SELECT 
    [Extent1].[UserId] AS [UserId], 
    [Extent1].[Name] AS [Name], 
    [Extent1].[IsActive] AS [IsActive]
FROM   [dbo].[User] AS [Extent1]
INNER JOIN [dbo].[Location] AS [Extent2] ON [Extent1].[UserId] = [Extent2].[UserId]
INNER JOIN [dbo].[ApprovedUser] AS [Extent3] ON [Extent1].[UserId] = [Extent3].[ApprovedUserId]
WHERE 1 = [Extent1].[IsActive]

Upvotes: 2

Related Questions