小编典典

“ LINQ to Entities不支持LINQ表达式节点类型'Invoke'”-烦死了!

c#

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

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

但是,我得到上述错误。似乎我通过从函数构建谓词来使所有事情正确无误。有任何想法吗?谢谢。


阅读 636

收藏
2020-05-19

共1个答案

小编典典

您正在尝试在…中传递任意.NET函数。实体框架如何希望将其转换为SQL?您可以将其改为取一个Expression<Func<int, bool>>,然后Where从中构建子句,尽管这并不是 特别
容易,因为您需要使用其他参数表达式重写表达式(即替换原始表达式中的任何参数表达式)表示的树u.RelationTypeId)。

老实说,为了仅u.RelationTypeId在用于创建表达式树的lambda表达式中指定要传递到方法中,最好还是使用:

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