簡體   English   中英

從T SQL到LINQ的NOT IN子選擇?

[英]NOT IN sub select from T SQL to 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;

您可以嘗試這樣的事情:

// 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));
var query = from a in _Context.Table1
            where _Context.Table2.Any(ta=>ta.SecondaryId== a.TableId) == false
            select a;

您可能能夠做到這一點……雖然不漂亮……但鑒於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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM