Is it possible to use Func<entity> in Where method to hot swap them?

时间:2018-09-19 08:21:05

标签: c# entity-framework lambda

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?

2 个答案:

答案 0 :(得分:2)

如果您的Filter.Func(e)方法返回的是Expression<Func<T, bool>>,而不是Func<T, bool>(因为您使用的是EF),那么您应该可以执行以下操作。

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

明确获得谓词的第一位将迫使EF不要在表达式中包含EF无法处理的Filter.Func(e)的执行,这就是为什么您要获取异常的原因。

答案 1 :(得分:0)

我认为您的Func如下图

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();

或者直接使用Func

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

list.Where(s).ToList();