Joh*_*han 4 c# asp.net lambda entity-framework
我为EF实体做了一个扩展方法:
public static IEnumerable<T> WildcardSearch<T>(this IEnumerable<T> entity,
string param, Func<T,
string> 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();
Run Code Online (Sandbox Code Playgroud)
如果我尝试使用它,我会得到上面的例外.
但是,如果我直接在我的集合上运行(我假设的)相同的代码,它就像预期的那样工作.
为什么我会得到异常,有没有办法解决这个问题?
类似的线程建议改变类型IQueryable,但它似乎没有帮助.
//this works
result = context.FOO.Where(x =>
SqlFunctions.PatIndex(id, x.Id) > 0).ToList();
Run Code Online (Sandbox Code Playgroud)
它需要IQueryable<T>和Expression<Func<...>>; 不幸的是,这意味着重建表达式树 - 例如:
public static IQueryable<T> WildcardSearch<T>(this IQueryable<T> entity,
string param, Expression<Func<T, string>> selector)
{
var lambda = Expression.Lambda<Func<T, bool>>(
Expression.GreaterThan(
Expression.Call(
typeof(SqlFunctions), "PatIndex", null,
Expression.Constant(param, typeof(string)),
selector.Body),
Expression.Constant(0)),
selector.Parameters);
return entity.Where(lambda);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6260 次 |
| 最近记录: |