[英]Transform SQL query to Linq left join clause incorrect
我正在嘗試選擇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查詢中應該更改什么嗎?
試試這個
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 ==設置為空!!!
抱歉,Sql和LINQ查詢在表選擇方面有些不同。 我對此感到抱歉,因為我在發布問題時嘗試使用其他Linq,但是主要問題在於join子句
(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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.