Implementing “where not exists” with NHibernate QueryOver

左心房为你撑大大i 提交于 2019-12-19 10:29:35

问题


Using the new QueryOver API in NHibernate, I need to do something equivalent of:

select c.*
from Category c
where not exists (
    select *
    from CategoryProduct cp
    where cp.CategoryID = c.Id
    and cp.ProductID = 'DogFood'
)

In other words: "Give me all categories that doesn't contain dog food".

My initial thought was something like:

IEnumerable<Category> FindCategoriesWithoutProduct(Product product)
{
    return _session
        .QueryOver<Category>()
        .Where(c => c.Products.Contains(product))
        .List();
}

However, this makes NHibernate.Impl.ExpressionProcessor blow up with an "unrecognised method call" on System.Collections.Generic.ICollection<T>.Contains().

I assume there must be some other way to do this, probably involving an ICriterion, but my searches here and on Google have returned nothing useful.


回答1:


I'm just running in the same problem, and possible solution is:

Category aliasCategory = null;
CategoryProduct aliasCategoryProduct = null;

var qcp = QueryOver.Of<CategoryProduct>(() => aliasCategoryProduct)
          .Where(() => aliasCategoryProduct.ProductID == "DogFood")
          .Where(() => aliasCategory.Id == aliasCategoryProduct.CategoryID)
          .DetachedCriteria;

return _session.QueryOver<Category>(() => aliasCategory)
               .Where(Subqueries.NotExists(qcp));

It works on my similar criteria.




回答2:


Not tested, but something like this

IEnumerable<Category> FindCategoriesWithoutProduct(Product product)
{
    CategoryProduct categoryProductAlias = null;
    var subQuery = QueryOver.Of<CategoryProduct>(() => categoryProductAlias)   
        .Select(x => categryProductAlias.ID)
        .Where(() => categoryProductAlias.ProductID == "DogFood");

    Category categoryAlias = null;
    return _session
        .QueryOver<Category>(() => categoryAlias)
        .WithSubquery.WhereProperty(() => clientAlias.Id).NotIn(subQuery)
        .List();
}


来源:https://stackoverflow.com/questions/5646947/implementing-where-not-exists-with-nhibernate-queryover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!