NHibernate标准查询多个级别的子集合

时间:2012-08-10 13:38:48

标签: nhibernate

我在如何对代码中没有相互引用的2个表执行查询方面遇到了很多困难,例如,我有

Customer -> Product* where customer and product have reference to each other

和     库存 - >产品*其中产品没有参考库存

我想找到所有没有库存产品的客户。

到目前为止我已经这样做了

var subQueryInv= DetachedCriteria.For<Inventory>();
        subQueryInv
            .Add(Restrictions.IsNotNull("Product.Id"))
            .SetProjection(Projections.Property<Inventory>(inv=> inv.Product.Id));

        var subQueryProd = DetachedCriteria.For<Product>();
        subQueryTire
            .Add(Subqueries.PropertyNotIn("Id", subQueryInv))
            .SetProjection(Projections.Property<Tire>(prod=> prod.Customer.Id));

        var subQueryCust= DetachedCriteria.For<Customer>();
        subQueryCust
            .Add(Subqueries.PropertyIn("Id", subQueryProd))
            .SetProjection(Projections.Property<TireSet>(cust => cust.Id));

这有效,但是查询非常有效,它为Inventory部分生成这样的SQL     ...在哪里Product.Id NOT IN(从库存中选择Inventory.ProductId WHERE Inventory.ProductId不为空)

因此,对于每个产品记录,它都在查询整个Inventory表。如何让子查询像这样引用父ID:

    ...WHERE Product.Id NOT IN (SELECT Inventory.ProductId FROM Inventory WHERE Inventory.ProductId IS NOT NULL AND Inventory.ProductId = Product.Id)

1 个答案:

答案 0 :(得分:2)

您可以使用别名来引用主要条件

var subQueryInv= DetachedCriteria.For<Inventory>();
    .Add(Restrictions.IsNotNull("Product.Id"))
    .Add(Restrictions.PropertyEq("Product", "product"))
    .SetProjection(Projections.Property<Inventory>(inv => inv.Product.Id));

var subQueryProd = DetachedCriteria.For<Product>("product");