mbue
mbue

Reputation: 1632

NHibernate / LINQ: how to write this JOIN query?

I got an entity E having a many-to-many relation with entity F. Now i want to count all instances of E which are related to a certain instance of F.

In good old HQL-times, I used the following query:

select count(*) from E e inner join e.fCollection f where f.id = :id

:id is the primary key of the relevant F instance. e.fCollection is the collection holding all F instances, e is related to.

With NH-to-LINQ, it doesn't seem possible to join with fCollection.

Any ideas? :) Thank you in advance

Upvotes: 2

Views: 1351

Answers (1)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

Try this:

e.Count(x => x.fCollection.Any(y => y.id == id));

This returns the number of es with at least one collection item with the specified id.
If you want the number of collection items that have the specified id, use this:

e.fCollection.Count(x => x.id == id);

Upvotes: 2

Related Questions