I have a generic type class Filter that has takes some lambda expressions to select values from the type so that the class is reusable. That class is used in another generic type class Search which will use Filter to select distinct items of the type which will eventually be used in a drop down list.
I removed the unimportant code for these.
public class Filter<T>
{
public string Name;
public Func<T, string> Key;
public Func<T, string> Value;
}
public class Search<T>
{
MyDBContext db = new MyDBContext();
IQueryable<T> Model = db.Stuff.OrderBy(a => a.TermID);
Filter filter = new Filter(
Name: "Term",
Value: a => a.TermID.ToString(),
Key: a => a.Term.TermType.Name
);
var filterItems = Model
.Select(a => new { Key = filter.Key(a), Value = filter.Value(a)})
.OrderBy(t => t.Key)
.Distinct()
.ToArray();
}
I get the run time error: The LINQ expression node type 'Invoke' is not supported in LINQ to Entities.
I have tried using strong types instead of anonymous types, and using Expression<Func<T,string>> in Filter.
After hours of searching and trying different things, I’m not sure how to make this work.
Thank you for your help.
Your problem can be expressed much more simply, eg this reproduces it:
It compiles fine but gives the same error at runtime because you are invoking a compiled function. That part “t => t.ID” is complied code (at least to IL) and linq cannot read this to convert it to SQL. It can only convert an expression tree to SQL. The solution to the above case is fairly simple, I’m not sure how this will translate to your situation but it should be possible.
There is also the option of moving the function call into linq to objects so that it doesn’t need to be translated to sql (everything after “AsEnumerable” is processed on the client). This allows much greater flexibility in what can be placed in the function and will eliminate the type of errors you are getting. This will also eliminate the need for call to SqlFunctions (see below). The downside is that more rows might be returned than needed from the server.
Your last problem is that EF doesn’t like the ToString method and you will need to use SqlFunctions.StringConvert which is fairly crappy. See here: int to string in Entity Framework