2013-02-20 73 views
0

我有这样的数据库结构:在NHibernate中选择没有多对多关系的项目?

Products 
    ProductId 

Categories 
    CategoryId 

ProductsInCategories 
    ProductId 
    CategoryId 

我需要找到所有没有在一个类别的产品。现在,我使用此代码:

var results = Session 
    .CreateCriteria<Product>() 
    .List<Product>() 
    .Where(product=> !product.Categories.Any()) 
    .ToList(); 

因此,我返回数据库中的所有产品,然后过滤它们。这是低效的,我需要一个更好的方法。

我试过这段代码:

var res = Session.QueryOver<Product>() 
    .Left.JoinQueryOver(product=> product.Categhories) 
    .Where(categories => !categories.Any()) 
    .TransformUsing(Transformers.DistinctRootEntity) 
    .List(); 

但它并没有在所有的工作。我尝试了一些变化,但是也没有奏效。

我该如何使用NHibernate执行此查询?

回答

1

试试这个:

var res = Session.QueryOver<Product>() 
    .WhereRestrictionOn(x => x.Categories).IsEmpty() 
    .List(); 
+0

谢谢,做它。这个API使用起来有点棘手! – Oliver 2013-02-20 13:17:05