views:

23

answers:

1

I have an function outside my EDM that I would like to include in some of my Linq to Entities expressions. The function returns an IEnumerable of Int. An example of how I might use it is:

context.Employees.Where(e => GetValidEmployeeIds().Contains(e.EmployeeId));

The function GetValidEmployeeIds is the function that is returning the IEnumerable. The result of this function isn't something that I can get from the database - I pretty much have to get it externally from the EDM.

When I execute the line of code I get "LINQ to Entities does not recognize the method" - which makes since. However if I break the call out of the expression it works fine:

var validEmployees = GetValidEmployeeIds(); 
context.Employees.Where(e => validEmployees.Contains(e.EmployeeId));

My question is: Is there anything I can do to instruct Linq to Entities to not parse the function as part of the expression? To instead parse the result of the function. I was hoping there was an attribute I could decorate the method with but haven't been able to find one.

Normally, I would be fine with just breaking out the call and not using it directly in the expression. However, I'm going to be using this call a lot and was hoping to clean up the code a bit.

+1  A: 

No, you'd need to move the function invocation:

I.e., this:

var q = Context.Entities.Where(e => e.Something == DoStuff());

...has to become:

var stuff = DoStuff();
var q = Context.Entities.Where(e => e.Something == stuff);

However, if you can put your function into an Expression, then you can use that directly:

var stuff = DoStuff();
Expression<Func<Entity, bool>> predicate = e => e.Something == stuff;
var q = Context.Entities.Where(predicate);

... so you may be able to clean up your cut and paste that way.

Craig Stuntz