views:

483

answers:

2

Hi

Is it possible to use a function import in a where clause in entity framework? I have tried the following, but I get a rather cryptic exception to which I cannot find any information about:

var q = MyContext.MyEntities.Where("MyContext.MyFunction(it.ID)")

(The function is set to return a Boolean)

System.Data.EntitySqlException: 'MyContext.MyFunction' cannot be resolved into a valid type constructor or function., near WHERE predicate, line 6, column 21..

Regards

Lee

A: 

I don't think you want to pass this expression as a string. You want a proper lambda expression like:

MyContext.MyEntities.Where( entity => MyContext.MyFunction(entity.ID ) );

jlew
Thanks Jeremy - however, as the function isn't returning an entity (just a Boolean) it doesn't exist in the class of MyContext (although I can successfully call it via and EntityClient).
Lee Atkinson
Well, where does it exist? Just call it on the right hand side of the => just like you would from anywhere else.
jlew
It doesn't exist as a member of the DataContext object as generated by the Entity framework) as it's not a entity-returning function - it's a boolean-returning.
Lee Atkinson
Take a look at the documentation of the Where extension method[1]. The Where method accepts a function (delegate) which accepts a typed Entity and returns a boolean. The lambda expression which I supplied (modified to be syntactically correct, since you pointed out that it exists somewhere other than MyContext), will work just fine as a filter for the Where method, and the result will be a collection of entities which "pass" the filter.[1] http://msdn.microsoft.com/en-us/library/system.linq.queryable.where.aspx
jlew
But that will result in the where clause being evaluated on the client, won't it?
Lee Atkinson
My bad, I didn't fully understand your question until now. Alex is absolutely right.
jlew
+1  A: 

The query you are trying to write is composing a call to a FunctionImport with a query over an EntitySet.

But because FunctionImports are wrappers around StoredProcedures, which are non-composable, this just won't work.

In order for something like this to work, theoretically the function would need to be a wrapper around something composable like a TVF (Table Value Function). But unfortunately TVFs aren't supported in the Entity Framework today.

Alex

Alex James
Lee Atkinson