问题
I have this database structure:
Products
ProductId
Categories
CategoryId
ProductsInCategories
ProductId
CategoryId
I need to find all the products that are not in a category. Right now, I use this code:
var results = Session
.CreateCriteria<Product>()
.List<Product>()
.Where(product=> !product.Categories.Any())
.ToList();
So I return all the products in my database, then filter them. This is inefficient, I need a better method.
I tried this code:
var res = Session.QueryOver<Product>()
.Left.JoinQueryOver(product=> product.Categhories)
.Where(categories => !categories.Any())
.TransformUsing(Transformers.DistinctRootEntity)
.List();
But it didn't work at all. I tried some variations but that didn't work either.
How should I perform this query with NHibernate?
回答1:
Try this:
var res = Session.QueryOver<Product>()
.WhereRestrictionOn(x => x.Categories).IsEmpty()
.List();
来源:https://stackoverflow.com/questions/14977508/select-items-with-no-many-to-many-relations-in-nhibernate