views:

679

answers:

2

I am manually creating the equivalent lambda:

var function = p => p.Child.Any(c => c.Field == "value");

I have a MethodInfo reference to the "Any" method used with Expressions built in code.

MethodInfo method = typeof(Queryable).GetMethods()
        .Where(m => m.Name == "Any" && m.GetParameters().Length == 2)
        .Single().MakeGenericMethod(typeof(Child));

My entities are: Parent 1---* Child

Child is a Navigation Property on Parent (p in the above lambda). The type of the property is EntityCollection as created by the designer.

I was looking for the proper way to reference the Any method to create that call. Marc gave me the answer how to get this here: http://stackoverflow.com/questions/439172/calling-a-method-from-an-expression

But it doesn't work for the entity framework. EntityCollection does not implement IQueryable, so how should the Any method be referenced.

+3  A: 

EntityCollection<T> doesn't implement IQueryable<T> so it's not surprising that this doesn't work, IMO.

Could you give more explanation of what you're trying to do? If you're expecting the query to be run on the database, my guess is that it's really not going to support that (given that EntityCollection<T> doesn't implement IQueryable<T>). If you want the query to be run locally, you should use Enumerable.Any instead of Queryably.Any.

EDIT: Having seen the updated collection, I believe you just want Enumerable.Any instead of Queryable.Any. Don't forget that if this is being provided as an expression tree, you won't actually be executing that code anyway. Presumably the framework understands Enumerable.Any as applied to an EntityCollection<T>

Jon Skeet
My answer was too large for a comment, please see my answer below.
blu
Please edit the question to clarify it, rather than adding a "non-answer".
Jon Skeet
I have updated the original question with clarifications, thanks
blu
A: 

You can cast EntityCollection to IQueryable by using the AsQueryable() extension method.