简体   繁体   English

LINQ for Entity Framework 4.0中的SQL子查询

[英]SQL Subquery in LINQ for Entity Framework 4.0

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. 我是LINQ和EF的新手,但是对于大多数查询,我还是能碰到过,但是这个让我完全困惑。 No matter what I try, it comes up in SQL Profiler as a big mess :-). 不管我尝试什么,它在SQL Profiler中都会带来很大的麻烦:-)。

I have two tables: Users and UsersProjects. 我有两个表:Users和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. 这是我用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. 在SQL中,这似乎是一个相当简单的子查询,但是在LINQ中,我感到困惑。

Thanks, 谢谢,

Jorin 乔林

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) 或(这是您在linq中的sql查询)

(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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM