【发布时间】:2012-09-08 12:03:03
【问题描述】:
我正在尝试用 Linq to Entity 语法编写以下 Left Outer Join 场景,但我终其一生都无法弄清楚如何实现它... 这是有效的 SQL strong> 我正在努力最终实现的目标:
选择 *
FROM 学生
左加入 ParentStudents ps ON ps.StudentId = s.StudentId AND ps.ParentId = '6D279F72-2623-459F-B701-5C77C52BA52F'
其中 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 记录,我希望那些与学生记录一起加入...
谢谢!
【问题讨论】:
标签: entity-framework linq-to-entities left-join