2015-01-15 50 views
0

試圖在這裏編寫一個LINQ查詢來從T SQL中複製NOT IN。這裏是我想要在LINQ中的SQL查詢:不是子選擇從T SQL到LINQ?

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; 
+0

店Table2.TableId列表中的等價,然後更改的LINQ to是這樣的:'哪裏idList.Any(X => X == a.TableId )'或'idList.All(x => x!= a.TableId)' – Reniuz

+0

由於@Christos概述的問題以及其他巨大的bug和缺失的功能,我會建議不要使用LinqToSQL。 – Aron

回答

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)); 
+0

@halit aggreed,但我不確定如果OP可以避免這種情況,因爲它使用LINQ到SQL,我不確定是否可以將任何''轉換爲SQL。 – Christos

+0

您的示例向sql server發送2個查詢。 IT可以通過使用連接或存在來完成1個查詢。但是你的查詢是完全正確的。只是性能問題:) – halit

+0

偉大的@Christos,使用你的第一個例子,產生排除記錄的列表,然後在實際的where子句中使用.Contains == false。謝謝! – Hardgraf

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