我正在尝试在Linq to Entity语法中编写以下Left Outer Join scenerio,我不能为我的生活弄清楚如何将它拉下来... 这是工作SQL 我正试图最终实现:
SELECT *
来自学生
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'
Bold中突出显示的部分是我跌倒的地方......无论数据库中是否有任何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记录,我希望那些记录与学生记录相结合......
谢谢!
答案 0 :(得分: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 };
引自here。
答案 1 :(得分:0)
感谢Joe提供的额外帮助....这并不能让我在那里,但我终于让它运行了。这是工作代码:
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();
}