EF扩展方法:"此功能只能从LINQ援引实体"。 [英] EF extension method: "This function can only be invoked from LINQ to Entities."

查看:424
本文介绍了EF扩展方法:"此功能只能从LINQ援引实体"。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 公共静态的IEnumerable< T> WildcardSearch< T>(这个IEnumerable的< T>的实体,
字符串参数,函数功能< T,
弦>选择器)
{
返回entity.Where(L => SqlFunctions .PatIndex(参数,选择器(1))大于0);
}

//例外:此功能只能从LINQ援引实体。
结果= context.FOO.WildcardSearch(ID,X => x.Id).ToList();



我得到上面的异常,如果我尝试使用它。



不过,如果我在我的收藏中运行(我认为)非常相同的代码直接,它可以作为intented。



为什么我的例外,是有什么办法可以解决这个问题?



相似的主题建议改变类型的IQueryable ,但它似乎并没有帮助。

  //这个作品
结果= context.FOO.Where(X => ;
SqlFunctions.PatIndex(ID,x.Id)大于0).ToList();


解决方案

它需要的IQueryable< ; T> 表达式来; Func键< ...>> ;不幸的是,这意味着重建的表达式树 - 例如:

 公共静态的IQueryable< T> WildcardSearch< T>(这IQueryable的< T>的实体,
字符串参数,表达式来; Func键< T,串>>选择器)
{
变种的λ= Expression.Lambda< Func键<吨,布尔>>(
Expression.GreaterThan(
Expression.Call(
typeof运算(SqlFunctions),PATINDEX,空,
Expression.Constant(参数中的typeof(串)),
selector.Body)
Expression.Constant(0)),
selector.Parameters);
返回entity.Where(拉姆达);
}


I have made an extension method to EF entities:

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

I get the exception above if I try to use it.

However, if I run (what I assume) the very same code directly on my collection, it works as intented.

Why do I get the exception, and is there any way to fix this?

Similar threads suggest changing the type to IQueryable, but it doesn't seem to help.

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

解决方案

It needs to be IQueryable<T> and Expression<Func<...>>; unfortunately this means rebuilding the expression tree - for example:

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

这篇关于EF扩展方法:&QUOT;此功能只能从LINQ援引实体&QUOT;。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆