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

这行得通,bt查询效率非常低,它正在为库存部分生成这样的SQL ...WHERE Product.Id 不在(从 Inventory 中选择 Inventory.ProductId NOT,其中 Inventory.ProductId 不为 NULL)

因此,对于每个产品记录,它正在查询整个库存表。 如何让子查询具有对父 Id 的引用,如下所示:

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

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

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

最新更新