0

I'm making a hot swappable filter for my entities that depend on a mode selected. I'd like to be able to call something like

list.Where(e => Filter.Func(e)).ToList();

With this

public class Filter() {
    public Func<CollectedDataRecord, bool> Func = (o) => true;
    //code that assigns other Func's depending on case
}

Basically that's it. But I get 'The LINQ expression node type 'Invoke' is not supported in LINQ to Entities.'

I've seen this question But I didn't get the solution.

Is it possible of I should make it in a different way. May be make Table Functions in SQL?

zORg Alex
  • 372
  • 2
  • 15
  • 1
    You mean something like this? `Expression> wherePredicate = p => p.Mode == Mode.FirstMode; list.Where(wherePredicate).ToList()`. – FCin Sep 19 '18 at 08:23
  • You should understand solution in a link you posted instead of finding a new way. The referenced link contains the best solution for your problem. Learn about `Expression` and `Func` and how predicates work and implement solution from the link. – FCin Sep 19 '18 at 08:29
  • what is the return type of `Filter.Func`? – Yacoub Massad Sep 19 '18 at 08:41
  • Yeah, now I get it. Thanks. – zORg Alex Sep 19 '18 at 09:54

2 Answers2

2

If your Filter.Func(e) method returns an Expression<Func<T, bool>>, and not a Func<T, bool> (since you are using EF) then you should be able to do the following.

var predicate = Filter.Func(e);
list.Where(predicate).ToList();

Explicitly getting the predicate first forces EF not to include the execution of the Filter.Func(e) in the expression, which EF cannot handle, which is why you get the exception you're getting.

Maarten
  • 22,527
  • 3
  • 47
  • 68
  • Brilliant. Exactly what I expected to see. I guess I wrote Expression in a wrong way, when tried to Ctrl + . to resolve missing using at first time. – zORg Alex Sep 19 '18 at 10:22
0

I think your Func would look like below

Func<listObjectType, bool> FilterFunc()
{
     Func<listObjectType, bool> s = delegate (listObjectType obj)
     {
           return obj == ""; //Here your code for comparison should go
     };
     return s;
}

list.Where(FilterFunc()).ToList();

or if you have Func available directly

Func<listObjectType, bool> s = delegate (listObjectType obj)
{
     return obj == ""; //Here your code for comparison should go
};

list.Where(s).ToList();
ManishM
  • 583
  • 5
  • 7
  • Last one. Thanks, but the question was answered. I just needed to change Func Func to Expression> Func. And it works brilliantly. As I intended. – zORg Alex Sep 19 '18 at 10:20