错误"LINQ to Entities中不支持LINQ表达式节点类型'Invoke'".在方法内的where子句中 [英] Error "The LINQ expression node type 'Invoke' is not supported in LINQ to Entities" in where clause inside the method

查看:97
本文介绍了错误"LINQ to Entities中不支持LINQ表达式节点类型'Invoke'".在方法内的where子句中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我执行查询时:

rs.Select(x => x.id).ToArray();

我收到此错误:

LINQ to Entities不支持LINQ表达式节点类型"Invoke"

这是产生错误的方法(可能是 func(x)):

This is the method that generates the error (probably func(x)):

public IQueryable<TEntity> Compare<TEntity>(IQueryable<TEntity> source, Func<TEntity, int> func)
{
     IQueryable<TEntity> res = source;

     if (!this.LBoundIsNull) res = res.Where(x => func(x) >= _lBound);
     if (!this.UBoundIsNull) res = res.Where(x => func(x) <= _uBound);

     return res;
}

我在这种模式下调用方法:

I invoke the method in this mode:

Document doc = new Document();
doc.Number = new RangeValues(lBound, null);

using (MyEntities db = new MyEntities())
{
    var rs = db.documents;
    if (doc.Number != null) rs = doc.Numero.Compare(rs, x => x.number);

    long[] id = rs.Select(x => x.id).ToArray();
}

怎么了?

推荐答案

要执行您想要的操作,您需要执行以下操作:

To do what you want you will need to do something like:

public static IQueryable<TEntity> Compare<TEntity>(IQueryable<TEntity> source, Expression<Func<TEntity, int>> func)
{
    IQueryable<TEntity> res = source;

    if (!LBoundIsNull) 
    {
        Expression ge = Expression.GreaterThanOrEqual(func.Body, Expression.Constant(_lBound));
        var lambda = Expression.Lambda<Func<TEntity, bool>>(ge, func.Parameters);
        res = res.Where(lambda);
    }

    if (!UBoundIsNull)
    {
        Expression le = Expression.LessThanOrEqual(func.Body, Expression.Constant(_uBound));
        var lambda = Expression.Lambda<Func<TEntity, bool>>(le, func.Parameters);
        res = res.Where(lambda);
    }

    return res;
}

如您所见,您将需要执行一些表达式树管道.您可以使用与以前相同的方法来调用该方法.

As you can see you'll need to do some expression-tree plumbing. You call the method in the same way as before.

现在...是否真的可以按照@jbl的建议使用 LinqKit ?是的...稍微摇一下魔杖...

Now... is it really possible to use LinqKit as suggested by @jbl? Yes... By shaking a little the magic wand...

using LinqKit;

public static IQueryable<TEntity> Compare<TEntity>(IQueryable<TEntity> source, Expression<Func<TEntity, int>> func)
{
    IQueryable<TEntity> res = source;

    if (!LBoundIsNull)
    {
        Expression<Func<TEntity, bool>> lambda = x => func.Invoke(x) >= _lBound;
        res = res.Where(lambda.Expand());
    }

    if (!UBoundIsNull)
    {
        Expression<Func<TEntity, bool>> lambda = x => func.Invoke(x) <= _uBound;
        res = res.Where(lambda.Expand());
    }

    return res;
}

请注意Invoke()Expand() LinqKit方法的使用.

Note the use of the Invoke() and Expand() LinqKit methods.

这篇关于错误"LINQ to Entities中不支持LINQ表达式节点类型'Invoke'".在方法内的where子句中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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