StockBreak
StockBreak

Reputation: 2885

Query NHibernate Properties with LINQ

I have the following (very simplified) domain:

public class Product
{
    public virtual int Id { get; set; }
    public virtual string Description { get; set; }
    public virtual IList<Category> Categories { get; set; }
}

public class Category
{
    public virtual int Id { get; set; }
    public virtual string Description { get; set; }
}

The many-to-many collection is mapped using the following XML:

<bag name="Categories" table="ProductsCategories">
  <key column="ProductID" />
  <many-to-many column="CategoryID" class="Category" />
</bag>

When I'm loading my categories using the product property all is working correctly:

Product product = ProductRepository.Find(1);
var categories = product.Categories;

The problem is that when I try to filter my collection, for example:

Product product = ProductRepository.Find(1);
var categories = product.Categories.Where(c => c.SomeProperty == someValue);

The query is not executed against the database but it uses LINQ to Objects to filter the result! Is it possible to solve this problem without using HQL and without the need to map a new entity called for example "OrderDetail"?

Upvotes: 0

Views: 514

Answers (2)

kͩeͣmͮpͥ ͩ
kͩeͣmͮpͥ ͩ

Reputation: 7856

You need to query the category, not the product's categories. (You can do what you originally wanted with ISession.Filter, but that didn't take LINQ last time I looked).

e.g.

from category in session.Linq<Category>
where category.Products.Contains(product) and category.SomeProperty == someValue
select category

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503859

The problem is that Categories is declared as

IList<Category> Categories

That means your query will use Enumerable.Where instead of Queryable.Where.

I'd expect NHibernate to support another interface implementing IQuerable<T>, which you'd use to declare your property, e.g.

public virtual IQueryableList<Category> Categories { get; set; }

I haven't used NHibernate in anger, so I don't know what the type actually is, but that's what you should be looking for.

Upvotes: 0

Related Questions