我有以下Transact-Sql,我试图转换为LINQ ...并挣扎。
SELECT * FROM Project
WHERE Project.ProjectId IN (SELECT ProjectId FROM ProjectMember Where MemberId = 'a45bd16d-9be0-421b-b5bf-143d334c8155')
非常感谢任何帮助......如果可能的话,我想用Lambda表达式来做。
提前致谢!
答案 0 :(得分:6)
GFrizzle打败了我。但这是一个C#版本
var projectsMemberWorkedOn = from p in Projects
join projectMember in ProjectMembers on
p.ProjectId equals projectMember.ProjectId
where projectMember.MemberId == "a45bd16d-9be0-421b-b5bf-143d334c8155"
select p;
作为一个纯粹的LINQ方法链版本的奖励:
var projectsMemberWorkedOn =
Projects.Join( ProjectMembers, p => p.ProjectId, projectMember => projectMember.ProjectId,
( p, projectMember ) => new { p, projectMember } )
.Where( @t => @t.projectMember.MemberId == "a45bd16d-9be0-421b-b5bf-143d334c8155" )
.Select(@t => @t.p );
答案 1 :(得分:5)
在这种情况下,您可以使用.Contains(),如下所示:
var projects =
from p in db.Projects
where db.ProjectMembers.Where(m => m.MemberId == "a45bd16d-9be0-421b-b5bf-143d334c8155").Select(pp => pp.ProjectID).Contains(p.ProjectID)
select p;
答案 2 :(得分:4)
不需要lambda,你只需要一个简单的LINQ连接:
From p in db.Projects _
Join m in db.ProjectMember On p.ProjectId Equals m.ProjectId _
Where m.MemberId = "a45bd16d-9be0-421b-b5bf-143d334c8155" _
Select p
答案 3 :(得分:3)
您可能需要 Any()运算符:
var q = db.Projects
.Where(p => db.ProjectMembers
.Where(pm => pm.MemberId == memberId)
.Any (pm => p.ProjectId == pm.ProjectId));
由于db.ProjectMembers.Where(...)
的结果集始终相同,因此您可以将其拆分以便只执行一次:
var projectMembers = db.ProjectMembers.Where(pm => pm.MemberId == memberId);
var q = db.Projects
.Where(p => projectMembers
.Any(pm => p.ProjectId == pm.ProjectId));