“LINQ to Entities 不支持 LINQ 表达式节点类型‘Invoke’"——难住了! [英] "The LINQ expression node type 'Invoke' is not supported in LINQ to Entities" - stumped!

查看:40
本文介绍了“LINQ to Entities 不支持 LINQ 表达式节点类型‘Invoke’"——难住了!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

稍后在我的 EF 中,我试图传入一个匿名函数以用作我的 Linq 查询的一部分.该函数将传入一个 INT 并返回一个 BOOL(u.RelationTypeId 是一个 INT).下面是我的函数的简化版本:

In my EF later, I'm trying to pass in an anonymous function to be used as part of my Linq query. The function would pass in an INT and return a BOOL (u.RelationTypeId is an INT). Below is a simplified version of my function:

public IEnumerable<UserBandRelation> GetBandRelationsByUser(Func<int, bool> relation)
{
    using (var ctx = new OpenGroovesEntities())
    {
        Expression<Func<UsersBand, bool>> predicate = (u) => relation(u.RelationTypeId);

        var relations = ctx.UsersBands.Where(predicate);

        // mapping, other stuff, back to business layer
        return relations.ToList();
    }
}

但是,我收到了上述错误.通过从函数构建谓词,我似乎一切都正确.有任何想法吗?谢谢.

However, I get the error stated above. It seems like I'm going everything correct by building a predicate from the function. Any ideas? Thanks.

推荐答案

您正在尝试将任意 .NET 函数传递到...实体框架如何希望将其转换为 SQL?您可以将其更改为采用 Expression> 代替,并从中构建 Where 子句,尽管它不会是 尤其 容易,因为您需要用不同的参数表达式重写表达式(即用调用u.RelationTypeId 的表达式替换原始表达式树中的任何参数表达式).

You're trying to pass an arbitrary .NET function in... how could the entity framework hope to translate that into SQL? You can change it to take an Expression<Func<int, bool>> instead, and build the Where clause from that, although it won't be particularly easy, because you'll need to rewrite the expression with a different parameter expression (i.e. replacing whatever parameter expression is in the original expression tree with the expression of calling u.RelationTypeId).

老实说,为了在用于创建表达式树以传递给方法的 lambda 表达式中指定 u.RelationTypeId,您最好只使用:

To be honest, for the sake of just specifying u.RelationTypeId in the lambda expression that you use to create the expression tree to pass into the method, you'd be better off just using:

public IEnumerable<UserBandRelation> GetBandRelationsByUser(
    Expression<Func<UsersBand, bool>> predicate)
{
    using (var ctx = new OpenGroovesEntities())
    {
        var relations = ctx.UsersBands.Where(predicate);

        // mapping, other stuff, back to business layer
        return relations.ToList();
    }
}

这篇关于“LINQ to Entities 不支持 LINQ 表达式节点类型‘Invoke’"——难住了!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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