views:

127

answers:

1

I'm new to LINQ and EF, but I've been able to stumble through for the majority of the queries I have, but this one has me completely confused. No matter what I try, it comes up in SQL Profiler as a big mess :-).

I have two tables: Users and UsersProjects. The goal of this query is to list all the users who are working on projects with the specified user. Here is the query as I have it written in SQL. It's a subquery, but I don't know of a way to simplify it further, but I'm open to suggestions there as well.

SELECT DISTINCT Users.FirstName, Users.LastName  
FROM Users INNER JOIN UsersProjects ON Users.ID=UsersProjects.UserID  
WHERE UsersProjects.ProjectID IN  
(SELECT ProjectID FROM UsersProjects WHERE UserID=@UserID)  

Anybody able to help?? It seems like a fairly simple subquery in SQL, but in LINQ, I'm baffled.

Thanks,

Jorin

A: 

Something like this I guess:

from u in Users
from projectId in UsersProjects.Where(up => up.UserId == @userId).Select(p => p.ProjectId)
where u.UsersProjects.Any(up => projectId == up.ProjectId)
select u

or (it's your sql query in linq)

(from u in Users
join up in UsersProjects on @userId equals up.UserId
where u.UsersProjects.Any(up2 => up2.ProjectId == up.ProjectId)
select u).Distinct()
MeF Corvi
No, that just basically connects the users to the usersprojects. All it returns is the user info for the user that exists in the usersprojects. For further reference, that query in the profiler appears as SELECT [Extent1].[ID] AS [ID], [Extent1].[FirstName] + N' ' + [Extent1].[LastName] AS [C1]FROM [dbo].[Users] AS [Extent1]WHERE EXISTS (SELECT 1 AS [C1] FROM [dbo].[UsersProjects] AS [Extent2] WHERE ([Extent1].[ID] = [Extent2].[UserID]) AND (1 = [Extent2].[UserID]))
Jorin
I'm sorry. My first query was definitely wrong. New query returns correct result but I'm not sure if it's possible to do query without sub-select.
MeF Corvi
Awesome! That works perfect...and it actually makes sense too. I played with it in LINQPad and was kind of able to reverse engineer what was going on in that "Any" lambda expression and I think I get it. Much thanks, MeF!
Jorin