6

我有以下 Transact-Sql 正在尝试转换为 LINQ ...并且正在苦苦挣扎。

SELECT * FROM Project
WHERE Project.ProjectId IN (SELECT ProjectId FROM ProjectMember Where MemberId = 'a45bd16d-9be0-421b-b5bf-143d334c8155')

任何帮助将不胜感激......如果可能的话,我想用 Lambda 表达式来做。

提前致谢!

4

4 回答 4

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 );
于 2008-12-09T05:43:10.837 回答
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;
于 2008-12-09T05:11:50.153 回答
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
于 2008-12-09T05:36:01.040 回答
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));
于 2008-12-09T05:52:39.227 回答