实体框架中的LINQ to Entities不支持LINQ表达式节点类型"Invoke"

zah*_*bas 23 c# linq expression entity-framework predicate

任何人都可以帮助我解决我的问题.我使用下面给出的代码:

public IEnumerable<InvoiceHeader> Getdata(Expression<Func<InvoiceHeader, bool>> predicate)
{
    return AccountsContext.InvoiceHeaders.Include("Company").Include("Currency")
        .Include("BusinessPartnerRoleList").Include("DocumentType")
        .Where(predicate);
}
Run Code Online (Sandbox Code Playgroud)

.....

在我的代码中我使用如下

Expression<Func<InvoiceHeader, bool>> predicate = PredicateBuilder.True<InvoiceHeader>();
predicate = predicate.And(o => o.CompanyId == oInvoiceHeader.CompanyId);
List<InvoiceHeader> lstInvheader=Getdata(predicate).ToList();
Run Code Online (Sandbox Code Playgroud)

通过这样做,我得到了例外.[System.NotSupportedException] --- {"LINQ to Entities中不支持LINQ表达式节点类型'Invoke'."}

Len*_*rri 49

使用Joe Albahari在LINQKIT中提供的AsExpandable()方法可以解决这个问题.他PredicateBuilder是我看到你正在使用的那个创造者.

如果使用Entity Framework进行查询,请将最后一行更改为:

return objectContext.Products.AsExpandable().Where(predicate);

你可以抓住LINQKIT DLL 这里或通过NuGet包安装在这里.

它肯定会解决你的问题,因为它解决了我的问题.


Yeo*_*nho 1

Linq to EF 查询被转换为 SQL。该异常意味着运行时无法将您的代码转换为 SQL 查询,因为 SQL 不支持它。

您可以更改代码以省略 SQL 不支持的部分,或者您可以先通过调用 .AsEnumerable() 从数据库中提取数据,如下所示,然后您可以执行所有操作,因为它是 Linq-to-Objects

public IEnumerable<InvoiceHeader> Getdata(Expression<Func<InvoiceHeader, bool>> predicate)
{
    return AccountsContext.InvoiceHeaders.Include("Company").Include("Currency")
        .Include("BusinessPartnerRoleList").Include("DocumentType")
        .AsEnumerable()
        .Where(predicate);
}
Run Code Online (Sandbox Code Playgroud)

  • 在 .AsEnumerable() 之后执行 where 意味着所有记录都将被吸入。使用此建议时要格外小心。 (12认同)