EF扩展方法:“只能从LINQ到实体调用此函数。”

我为EF实体做了一个扩展方法:

public static IEnumerable WildcardSearch(this IEnumerable entity, string param, Func selector) { return entity.Where(l => SqlFunctions.PatIndex(param, selector(l)) > 0); } //exception: This function can only be invoked from LINQ to Entities. result = context.FOO.WildcardSearch(id, x => x.Id).ToList(); 

如果我尝试使用它,我会得到上面的例外。

但是,如果我直接在我的集合上运行(我假设的)相同的代码,它就像预期的那样工作。

为什么我会得到exception,有没有办法解决这个问题?

类似的线程建议将类型更改为IQueryable ,但它似乎没有帮助。

 //this works result = context.FOO.Where(x => SqlFunctions.PatIndex(id, x.Id) > 0).ToList(); 

它必须是IQueryableExpression> ; 不幸的是,这意味着重建表达式树 – 例如:

 public static IQueryable WildcardSearch(this IQueryable entity, string param, Expression> selector) { var lambda = Expression.Lambda>( Expression.GreaterThan( Expression.Call( typeof(SqlFunctions), "PatIndex", null, Expression.Constant(param, typeof(string)), selector.Body), Expression.Constant(0)), selector.Parameters); return entity.Where(lambda); }