where where子句使用linq

时间:2016-04-25 07:30:08

标签: linq linq-to-sql

尝试将具有2个where子句的查询转换为linq并获取一些错误。有人可以帮我吗?

原始查询:

select id 
from student 
where suId 
in (select suId 
    from subjects
    where cid 
    in (select id 
        from chapters 
        where chapter='C203'))

LINQ查询:

 var query = (from s in dc.students
        let subs = (from su in dc.subjects
                        where su.cid == Convert.ToInt32(from c in dc.Chapters
                                                            where c.chapter == 'Ç203'
                                                            select c.id) //Single chapter id will be returned
                        select su.suid)
        where subs.Contains(s.sid)
        select s.id).ToArray();

编译应用时,我的错误低于2

  1. ' System.Linq.IQueryable'不包含'包含'的定义和最好的扩展方法重载' System.Linq.ParallelEnumerable.Contains(System.Linq.ParallelQuery,TSource)'有一些无效的论点
  2. 实例参数:无法转换为System.Linq.IQueryable'到' System.Linq.ParallelQuery'

1 个答案:

答案 0 :(得分:0)

由于Linq是懒惰加载的所有内容,所以您不需要将所有内容都塞入单个语句中;你可以这样做:

var chapterIds = dc.Chapters
    .Where(c => c.Chapter == "C023")
    .Select(c => c.Id);
var subjectIds = dc.Subjects
    .Where(s => chapterIds.Contains(s.Cid))
    .Select(s => s.Suid);
var students = dc.Students
    .Where(s => subjectIds.Contains(s.Suid))
    .Select(s => s.Sid)
    .ToArray();

这样,您可以通过查看返回的内容来调试每个子查询。

但是,查看原始选择,您可以将整个内容重写为Join并摆脱烦恼问题:

var students = dc.Chapters.Where(c => c.Chapter == "C023")
    .Join(dc.Subjects,
        c => c.Id,
        s => s.Cid,
        (chapter, subject) => subject)
    .Join(dc.Students,
        subj => subj.Suid,
        student => student.Suid,
        (subj, st) => st.Sid)
    .ToArray();