tl; dr version:我需要这个sql语句来使用linq到EF
这是SQL中的查询:
select
stu.SyStudentId,
rtrim(stu.StuNum) as StudentNumber,
stu.SSN,
stu.FirstName,
stu.LastName,
Email,
OtherEmail,
stu.StartDate,
case
when (systa.category = 'E') then 'Enrolled'
when (systa.category = 'A') then 'Active'
else 'This should never happen'
end as StatusCategory,
rtrim(schsta.Code) as SchoolStatusCode,
pic.StudentPicture,
case when (stu.DateLstMod > isnull(pic.DateLstMod,'1900-1-1'))
then stu.DateLstMod
else pic.DateLstMod
end as DateLstMod
from
SyStudent stu
inner join syschoolstatus schsta on schsta.syschoolstatusid = stu.syschoolstatusid
inner join SyStatus systa on systa.SyStatusId = schsta.SyStatusId
left outer join cmstudentpicture pic on pic.systudentid = stu.systudentid
where stu.sycampusid = 6
and systa.category in ('E','A')
丑陋的查询,继承自旧系统..
我正在努力获得一些利用实体框架的服务。我试图使用基于方法的语法使此查询工作。我首先得到了我要加入的所有对象的列表:
var students = ctx.syStudents.ToList(); //root
var statusCode = ctx.SySchoolStatus.ToList(); //inner
var status = ctx.syStatus.ToList(); //inner
var picture = ctx.CmStudentPictures.ToList(); //left outer
'ctx'是我的dbcontext类。
我到目前为止的查询是:
var query = students
.GroupJoin(statusCode,
student => student.SySchoolStatusID,
statuscode => statuscode.SySchoolStatusID,
(student, studentStatusCode) => new
{
StudentName = student.FirstName
});
显然没有完全实现,但我想知道这是否是执行此操作的最佳方式,因为我将有几个内连接,然后是左外连接,或者是否有更好的,更可读的方法来完成这项工作?
答案 0 :(得分:1)
我肯定会建议使用lambda语法进行连接的查询语法。
尝试以下几点:
var result =
from stu in SyStudent
join schsta in syschoolstatus on stu.syschoolstatusid equals schsta.syschoolstatusid //inner
join systa in SyStatus on schsta.SyStatusId equals systa.SyStatusId //innner
from pic in cmstudentpicture.Where(x => x.systudentid = stu.systudentid).DefaultIfEmpty() //outer
where stu.sycampusid = 6
select new{
stu,
schsta,
systa,
pic
};