Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate 3.1 Linq with Contains and Any

We are in the process of upgrading to NH3.1 which is going well - everything is working as far as we can tell with existing code. One of the motivations to move to NH3 from 2 has been to leverage the Linq support and generally it is working really well. However I am struggling with some more complex where clauses, specifically when I want to check based on a sub-collection:

var results = from r in registrations 
              where ( 
                         from p in persons 
                         where p.ExplicitManagers.Any(m => m.Manager == manager) 
                         select p 
                     ).Contains(r.Registrant) 
              select r; 

where the model is:
p is a Person and a registration r has a registrant of type Person
p contains a collection of ExplicitManager associative entities which hold a reference to another Person (manager).

note: registrations is an IQueryable<Registration>.Query() and persons in an IQueryable<Person>.Query().
Essentially I am trying to restrict the registrations to where person1 is an explicit manager of p. I can do this via joins but not through the Contains subquery.

I get the following error:

"System.InvalidOperationException : Sequence contains more than one matching element"

the reason for doing this as a sub-query is because ultimately I need to externalize the logic for checking the managers to make it reusable (it actually is more complex but I have simplified it for this example because it is the Any within a Contains which is causing the grief).

Contains seems to work fine when not having a sub-query with Any. Is this something I am doing wrong, or is it something unsupported or a bug, and is there another way of achieving the same thing?

Many thanks for any help you can give.

like image 415
IThasTheAnswer Avatar asked May 17 '11 10:05

IThasTheAnswer


1 Answers

Whilst Contains doesn't seem to work properly, using Any does:

var results = from r in registrations 
              where ( 
                         from p in persons 
                         where p.ExplicitManagers.Any(m => m.Manager == manager) 
                         select p 
                     ).Any(p=>p == r.Registrant) 
              select r; 
like image 78
IThasTheAnswer Avatar answered Oct 13 '22 17:10

IThasTheAnswer