views:

30

answers:

2

I have a session criteria statement (Fluent NHibernate) that does not seem to filter the child collection even though I have Expressions/Restrictions defined.

ICriteria criteria = session.CreateCriteria(typeof(MyClass));
criteria.CreateAlias("MyCollection", "MC");
criteria.Add(Restriction.Eq("MC.Property", value));
IList<MyClass> list = criteria.List<MyClass>();

This returns all the objects of type MyClass that have MyCollection.Property = value, however MyCollection is not filtered to MyCollection.Property = value

It seems like only the Root objects get filtered.

Thanks.

+2  A: 

That's correct, it will only filter the root entity. If the query changed the items in the collection of the root entity you could have a terrible problem: if you save the entity again, items that were filtered off of the collection will be removed of the realtionship permanently! And sure nobody wants that.

If you want that behaviour you'll have to do it manually (via foreach after the entities were loaded), although I wouldn't recomend that for the reason above. My sugestion is to make the entity in the collection the root of the query.

Pedro
Thanks for the advice. 1+ for explaining why I wouldn't want to do it!
a432511
+1  A: 

I've only found a few dodgy links about doing that - so this is at your own risks :).

It seems it should work if you add the following:

criteria.CreateCriteria("MC", JoinType.LeftOuterJoin);

I wouldn't recommend it though as per Pedro's answer.

Goblin
thanks! 1+ and correct answer
a432511