我正在尝试选择Unlock表中不存在的MatchingObjects,我有以下SQL查询:
select a.* from MatchingObjects a
left join Unlocks b
on a.ObjectCategoryId = b.ObjectCategoryId
left join Members c
on b.StudentId = c.Id
and b.StudentId = @studentId
where b.ObjectCategoryId is null
and c.id is null
order by a.ObjectCategoryId
和LINQ查询
var query = (from d in db.ObjectCategories
join a in db.MatchingObjects on d.Id equals a.ObjectCategoryId into grp3
join b in db.Unlocks
on d.Id equals b.ObjectCategoryId into grp1
from m in grp1.DefaultIfEmpty()
join c in db.Members
on m.StudentId equals c.Id into grp2
from n in grp2.DefaultIfEmpty()
where m.ObjectCategoryId == null
&& n.Id == null
orderby d.Id).AsEnumerable()
;
但是,LINQ查询在SQL查询中没有显示与我想要的结果相同的结果。你能告诉我在LINQ查询中应该改变什么吗?
答案 0 :(得分:1)
答案 1 :(得分:0)
尝试这个
var query = from m in db.MatchingObjects.Where(w => w.ObjectCategoryId == null)
join u in db.Unlocks.Where(w => w.studentId == @studentId)
on m.ObjectCategoryId equals u.ObjectCategoryId into joinedU
from ju in joinedU.DefaultIfEmpty()
join m in db.Members.Where(w => w.id == null)
on ju.StudentId equals m.Id into joinedM
from jm in joinedM.DefaultIfEmpty()
select m;
但你的请求有点奇怪。您通过ObjectCategoryId进行连接,并在Where子句中放置ObjectCategoryId == null !!!
答案 2 :(得分:0)
(from d in db.ObjectCategories
join a in db.MatchingObjects
on d.Id equals a.ObjectCategoryId into grp3
join b in db.Unlocks
on d.Id equals b.ObjectCategoryId into grp1
from m in grp1.DefaultIfEmpty()
join c in db.Members
on m.StudentId equals studentId into grp2
from n in grp2.DefaultIfEmpty()
where m.ObjectCategoryId == null
where n.Id == null
orderby d.Id).AsEnumerable()
/* this is the correct one */
join c in db.Members
on m.StudentId equals studentId into grp2
/* the below was the original incorrect join clause*/
join c in db.Members
on m.StudentId equals c.Id into grp2