2012-01-24 87 views
0

我試圖將SQL「NOT IN」表達式轉換爲LINQ,並且我發現我應該使用「Contains」選項。 我有2個表:LINQ to nHibernate - 將SQL「NOT IN」表達式轉換爲LINQ

ProductsGroups   Products      
--------------   ---------  
id      product_id  
product_id    product_name 

我的查詢是這樣的:

var innerQuery = from pg in Session.Query<ProductsGroups>  
select pg.product_id;  

var Query = from p in Session.Query<Products>       
where !innerQuery.Contains(p.product_id)       
select new {p.product_id, p.product_name}; 

但是,NHibernate的生成SQL是錯誤的:

select p.product_id, p.product_name  
from Products p  
where not (exists (select product_id      
from ProductsGroups pg     
where p.product_id = pg.id)) 

「去哪兒」 的條款是不在右側字段中,它將product_id與progucts組ID進行比較。 有誰知道我該如何解決它?

,我發現同時解決的辦法是先查詢列表轉換,然後 使用這個列表中第二個查詢:

var innerQuery = (from pg .....).ToList(); 

然後,NHibernate的翻譯「包含」表達爲「NOT IN 」因爲我想:

select p.product_id, p.product_name  
from Products p  
where not (p.product_id in (1,2,3,4)) 

回答

0

我不知道,但我認爲你正在運行到b/C包含一個問題,確定某個元素是集合中‘使用默認的相等比較’。 (MS文檔)我假設你的產品組映射將它指定爲Id屬性。所以從nHibernate的角度來看,這是用來確定相等性的價值。