具有多对多的NHibernate查询

时间:2011-08-16 16:08:01

标签: nhibernate queryover

情况如下: 1.产品属于很多类别, 2.类别有很多产品。

class Product
{
    public int Id { get; set; }
    public List<Category> Categories { get; set; }
}

class Category
{
    public int Id { get; set; }
    public List<Product> Products { get; set; }
}

如何拥有所有产品,其中每个产品都属于id = 2和3和4的类别。如何处理查询? 目前我使用动态创建的hql:

select p from Product p where 
exists (select c.id from p.Categories c where c.Id = 2) 
and exists (select c.id from p.Categories c where c.Id = 3)
and exists (select c.id from p.Categories c where c.Id = 4)

映射是:

public class ProductMap : ClassMap<Product>
{
    public ProductMap()
    {
        Id(x => x.Id);
        HasManyToMany(x => x.Categories)
            .Table("product_category")
            .ParentKeyColumn("product_id")
            .ChildKeyColumn("category_id");
    }
}

public class CategoryMap : ClassMap<Category>
{
    public CategoryMap()
    {
        Id(x => x.Id);
        HasManyToMany(x => x.Products)
            .Table("product_category")
            .ParentKeyColumn("category_id")
            .ChildKeyColumn("product_id");
    }
}

1 个答案:

答案 0 :(得分:0)

试试这个,也许是有帮助的:

Category categoryAlias = null;
session.QueryOver<Product>()
  .JoinAlias(product => product.Categories, () => categoryAlias)
  .WhereRestrictionOn(() => categoryAlias.Id).IsIn(new [] { 2, 3, 4 })
  .List();