【问题标题】:LINQ to nHibernate - translating SQL "NOT IN" expression to LINQLINQ to nHibernate - 将 SQL“NOT IN”表达式转换为 LINQ
【发布时间】:2012-01-24 08:04:46
【问题描述】:

我尝试将 SQL “NOT IN” 表达式转换为 LINQ,我发现我应该使用“包含”选项。 我有 2 张桌子:

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))

“where”子句不在正确的字段中,它将 product_id 与产品组 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))

【问题讨论】:

    标签: linq-to-nhibernate sql-to-linq-conversion


    【解决方案1】:

    我不确定,但我认为您遇到了问题 b/c contains 通过“使用默认相等比较器”确定元素是否在集合中。 (MS 文档)我假设您的产品组映射将其 Id 指定为 Id 属性。因此,从 nHibernate 的角度来看,这是用于确定相等性的值。

    【讨论】:

      猜你喜欢
      • 2011-03-04
      • 2015-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多