Can I use custom delegate method in Where method of Entity Framework?

前端 未结 1 546
情话喂你
情话喂你 2021-01-06 05:24
Where(this IQueryable source, Expression> predicate);

I pass parameter to Where metho

1条回答
  •  伪装坚强ぢ
    2021-01-06 05:55

    No.

    The Entity Framework needs to be able to see everything that is being attempted.

    So if you simply did something like this:

    queryable.Where(f => DelegateFunc(f));
    

    Where the definition of DelegateFunc looks like this:

    public bool DelegateFunc(Foo foo)
    {
       return foo.Id > 4;
    }
    

    The Entity Framework has no way of peering inside the delegate, to crack it open and convert it to SQL.

    All is not lost though.

    If your goal is to re-use common filters etc you can do something like this instead:

    public Expression> DelegateExpression{
       get{
           Expression> expr = f => f.Id > 4;
           return expr;
       }
    }
    
    queryable.Where(DelegateExpression);
    

    0 讨论(0)
提交回复
热议问题