0

tl;博士版本:我需要这个 sql 语句才能使用 linq to 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
   });

显然没有完全实现,但我想知道这是否是执行此操作的最佳方法,因为我将有几个内部连接,然后还有一个左外部连接,或者是否有更好、更易读的完成这项工作的方法?

4

1 回答 1

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
};
于 2013-03-25T15:38:31.757 回答