使用OR子查询nhibernate检查内部是否为null



我使用以下查询在where子句中包含一个子查询http://www.andrewwhitaker.com/blog/2014/10/24/queryover-series-part-8-working-with-subqueries/

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

这是它生成的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
    );

这就是我需要的。

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

最新更新