将SQL查询转换为Linq左连接子句不正确

时间:2016-04-18 08:50:11

标签: c# sql sql-server linq

我正在尝试选择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查询中应该改变什么吗?

这是型号: enter image description here

3 个答案:

答案 0 :(得分:1)

最好使用以下工具:

SQL-> LINQ转换器..

  1. <强> http://www.sqltolinq.com

  2. <强> http://www.linqpad.net/

答案 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)

很抱歉,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
相关问题