2016-08-11 87 views
0

我使用下面的查詢,包括where子句 http://www.andrewwhitaker.com/blog/2014/10/24/queryover-series-part-8-working-with-subqueries/使用OR子查詢nhibernate檢查null。

var popularProduct = session.QueryOver<Product>() 
    .WithSubquery.Where(()=>product.Id == 
     QueryOver.Of<TransactionHistory>() 
      .Select(tx => tx.Product.Id) 
      .OrderBy(tx => tx.Quantity) 
      .Desc 
      .Take(1) 
      .As<int>()) 
    .SingleOrDefault<Product>(); 

這裏面的子查詢是它產生

SELECT 
    * 
FROM 
    Production.Product this_ 
WHERE 
    this_.ProductID = (
     SELECT 
      TOP (1) this_0_.ProductID as y0_ 
     FROM 
      Production.TransactionHistory this_0_ 
     ORDER BY 
      this_0_.Quantity desc 
    ); 

的SQL這是我需要的。

SELECT 
    * 
FROM 
    Production.Product this_ 
WHERE 
    (this_.ProductID = (
     SELECT 
      TOP (1) this_0_.ProductID as y0_ 
     FROM 
      Production.TransactionHistory this_0_ 
     ORDER BY 
      this_0_.Quantity desc) OR this_.ProductID IS null) 
    ); 

var popularProduct = session.QueryOver<Product>() 
     .WithSubquery.Where(()=> product.Id == null || product.Id == 
      QueryOver.Of<TransactionHistory>() 
       .Select(tx => tx.Product.Id) 
       .OrderBy(tx => tx.Quantity) 
       .Desc 
       .Take(1) 
       .As<int>()) 
     .SingleOrDefault<Product>(); 
    It throws the following exception 
Could not determine member from (Convert(value(<>c__DisplayClass240).product.Id) == null) 

回答

0
I solved my own problem by using Disjunction 


Disjunction disjunction = Restrictions.Disjunction(); 
       disjunction.Add(Restrictions.On(() => product.Id).IsNull); 
       disjunction.Add(Subqueries.Where(() => product.Id == QueryOver.Of<RequirementNote>().Select(a => a.Id).Where(req => req.PID == product.PID).OrderBy(p => p.Id).Desc().Take(1).As<int>())); 

關於它的聯繫洽談。

http://www.andrewwhitaker.com/blog/2014/10/24/queryover-series-part-8-working-with-subqueries/