1

我正在尝试在 Linq to Entity 语法中编写以下 Left Outer Join 场景,但我终其一生都无法弄清楚如何将其完成...... 这是我试图最终实现的工作 SQL :

SELECT *
FROM Students s LEFT JOIN ParentStudents ps ON ps.StudentId = s.StudentId AND ps.ParentId = '6D279F72-2623-459F-B701-5C77C52BA52F'

WHERE s.TenantId = 3 AND s.FamilyId = '28833312-46eb-4a54-9132-8a7c8037cec5'

以粗体突出显示的部分是我失败的地方......我希望学生返回,无论数据库中是否有任何 ParentStudent 记录。

这是我最新的 LINQ to Entity代码不起作用

    public ICollection<ParentStudentListing> GetParentStudents(Guid FamilyId, Guid ParentId)
    {
        var query = from s in DataContext.Students
                    from ps in s.ParentStudents.DefaultIfEmpty()
                    where s.TenantId == CurrentUser.TenantId && s.FamilyId == FamilyId && ps.ParentId == ParentId
                    select new ParentStudentListing { StudentId = s.StudentId, FirstName = s.FirstName, MiddleName = s.MiddleName, LastName = s.LastName, RelationshipId = ps.RelationshipId, ParentStudentId = ps.ParentStudentId, isAllowedToPickUp = ps.isAllowedToPickUp, isEmergency = ps.isEmergency, isLiveIn = ps.isLiveIn, ParentId = ps.ParentId };

        return query.ToList();
    }

除非数据库中有非预期结果的 ParentStudent 记录,否则此代码不会带回学生。无论是否有 ParentStudent 记录,我都想带回学生,但是如果有 ParentStudent 记录,我希望那些与学生记录一起加入...

谢谢你!

4

2 回答 2

0

感谢乔的额外帮助....这并没有让我到达那里,但我终于让它运行起来了。这是工作代码:

    public ICollection<ParentStudentListing> GetParentStudents(Guid FamilyId, Guid ParentId)
    {
        var query = from s in DataContext.Students
                    join ps in DataContext.ParentStudents
                          on new { s.StudentId, ParentId = ParentId }
                      equals new { ps.StudentId, ps.ParentId } into ps_join
                    from ps in ps_join.DefaultIfEmpty()
                    where s.TenantId == CurrentUser.TenantId && s.FamilyId == FamilyId
                    select new ParentStudentListing { StudentId = s.StudentId, FirstName = s.FirstName, MiddleName = s.MiddleName, LastName = s.LastName, RelationshipId = ps.RelationshipId, ParentStudentId = ps.ParentStudentId, isAllowedToPickUp = ps.isAllowedToPickUp, isEmergency = ps.isEmergency, isLiveIn = ps.isLiveIn, ParentId = ps.ParentId };

        return query.ToList();
    }
于 2012-09-08T20:16:47.277 回答
0

这是我第一次尝试 LINQ 连接:

var query = from s in DataContext.Students
            join ps in s.ParentStudents on ps.ParentId equals s.ParentId into ps
            from ps in ps.DefaultIfEmpty()
            where s.TenantId == CurrentUser.TenantId && s.FamilyId == FamilyId                
            select new ParentStudentListing { StudentId = s.StudentId, FirstName = s.FirstName, MiddleName = s.MiddleName, LastName = s.LastName, RelationshipId = ps.RelationshipId, ParentStudentId = ps.ParentStudentId, isAllowedToPickUp = ps.isAllowedToPickUp, isEmergency = ps.isEmergency, isLiveIn = ps.isLiveIn, ParentId = ps.ParentId };

从这里引用。

于 2012-09-08T12:34:54.257 回答