2

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?

2
  • 2
    You would probably want to select the sublist into a list variable like: "var sublist = from t in approved_users select userId" Then use that variable in your main query IN clause. Commented Oct 12, 2017 at 19:24
  • It would help to see the three classes and their navigation properties. (Because you shouldn't join, but use navigation properties). Commented Oct 13, 2017 at 14:13

1 Answer 1

2

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.