views:

33

answers:

1

Using EF4. Assume I have this:

IQueryable<ParentEntity> qry = myRepository.GetParentEntities();  
Int32 n = 1;

What I want to do is this, but EF can't compare against null.

qry.Where( parent => parent.Children.Where( child => child.IntCol == n ) != null )  

What works is this, but the SQL it produces (as you would imagine) is pretty inefficient:

qry.Where( parent => parent.Children.Where( child => child.IntCol == n ).FirstOrDefault().IntCol == n )

How can I do something like the first comparison to null that won't be generating nested queries and so forth?

+3  A: 

Try this:

qry.Where( parent => parent.Children.Any( child => child.IntCol == n ));

Any in Linq translates to exists in sql.

If I understood Your queries correctly, this is what You need.

LukLed
Well, the SQL and the execution plan look so similar it's difficult for me to determine if it's better. This version does eliminate a cross apply, which seems good.
dudeNumber4
@dudeNumber4: It would be better if you wrote SQL query to translate to EF.
LukLed