方法内 where 子句中的错误 "The LINQ expression node type 'Invoke' is not supported in LINQ to Entities"

Error "The LINQ expression node type 'Invoke' is not supported in LINQ to Entities" in where clause inside the method

当我执行查询时:

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

我得到这个错误:

The LINQ expression node type 'Invoke' is not supported in LINQ to Entities

这是产生错误的方法(可能是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;
}

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

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

怎么了?

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

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

如您所见,您需要做一些表达式树管道。您以与之前相同的方式调用该方法。

现在...真的可以按照@jbl 的建议使用LinqKit 吗?是的...通过稍微摇动魔杖...

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 方法的使用。