NOT IN从T SQL到LINQ的子选择?

时间:2015-01-15 14:43:04

标签: c# sql-server linq

尝试在此处编写LINQ查询以从T SQL复制NOT IN。这是我在LINQ中想要的SQL查询:

select * from schema.Table1
where TableId NOT IN (select pa.TableId from schema.Table2 ta
where ta.SecondaryId = myParameter)

看了之前的帖子,但还没有完全发挥作用。

var query = from a in _Context.Table1
                    where a.TableId != _Context.Table2.Any(ta=>(ta.SecondaryId== myParameter))
                    select a;

3 个答案:

答案 0 :(得分:5)

您可以尝试这样的事情:

// get all the values that you want to exclude in a list.
var excluded = (from t in _Context.TableId
                select t.TableId
                where t.SecondaryId == myParameter).ToList();

// get all the items from Table1 that aren't contained in the above list
var query = from t in _Context.Table1
            where excluded.Contains(t.TableId)==false
            select t; 

// get all the values that you want to exclude in a list.
var excluded = _Context.TableId
                       .Where(x=>x.SecondaryId == myParameter)
                       .Select(x=>x.TableId)
                       .ToList();

// get all the items from Table1 that aren't contained in the above list
var query = _Context.Table1.Where(a=>!excluded.Any(a.TableId));

答案 1 :(得分:0)

var query = from a in _Context.Table1
            where _Context.Table2.Any(ta=>ta.SecondaryId== a.TableId) == false
            select a;

答案 2 :(得分:0)

你可能会这样......它不漂亮......但是鉴于LinqToSQL的有限功能设置它可能会起作用

IQueryable<Table2> excluded = from t in _Context.Table2
                           where t.SecondaryId == myParameter
                           select t;

// get all the items from Table1 that aren't contained in the above list
IQueryable<Table1> query = from t1 in _Context.Table1
                           join t2 in excluded on t1.TableId equals t2.TableId into foo
                           from e in foo.DefaultIfEmpty()
                           where e == null
                           select t;

此查询应该等效于

SELECT t1.*
FROM Table1 t1
LEFT JOIN (SELECT * FROM Table2 WHERE SecondaryId == @myParameter) t2 
          ON t1.TableId = t2.TableId
WHERE t2.TableId IS NULL