“无法创建类型的常量值。”如何避免 LINQ 查询中出现此错误?
我有这个方法:
public virtual IEnumerable<Invoice> GetHomePageInvoices(IList<Area> areas, FinancialYearLookup financialYear)
{
var homePageInvoices = _db.Invoices.Where(x => areas.Any(z => z.Id == 3)).ToList();
...
}
基本上,我试图找到该区域与参数区域中的任何发票相匹配的任何发票。
我收到错误:
无法创建“Models.Area”类型的常量值。仅有的 支持基本类型(“例如 Int32、String 和 Guid”) 在此背景下。
谁能解释为什么会发生这种情况以及如何解决?
I have this method:
public virtual IEnumerable<Invoice> GetHomePageInvoices(IList<Area> areas, FinancialYearLookup financialYear)
{
var homePageInvoices = _db.Invoices.Where(x => areas.Any(z => z.Id == 3)).ToList();
...
}
Basically I'm trying to find any invoices where the area matches with any of those in the parameter area.
I'm getting the error:
Unable to create a constant value of type 'Models.Area'. Only
primitive types ('such as Int32, String, and Guid') are supported in
this context.
Can anyone explain why this is happening and how to fix?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能在 Linq 提供程序(大概是 Linq to Entities)的上下文中使用
IList
- 只需预先提取 id 并使用适用于的
Contains
查询原语集合:此外,我假设您不想与固定值
3
进行比较 - 因此我相应地更改了您的查询 - 前提是Invoice
实体具有身份证属性。You cannot use an
IList<Area>
in the context of your Linq Provider (presumably Linq to Entities) - just extract the id's beforehand and use aContains
query which does work on a collection of primitives:Also I assume you did not want to compare with a fixed value of
3
- so I changed your query accordingly - provided theInvoice
entity has an Id property.一个。看起来你这里有一个错字:
但主要问题是
b.我猜您正在使用 Linq to Entities,但不清楚。无论如何,发生的情况是查询生成器试图将“areas.Any(...)”转换为 SQL,但它无法做到这一点,因为 Areas 不是数据库中的 IQueryable,而是本地变量。我建议您使用类似WhereIn自定义Linq运算符的内容,如此处或此处。这将构建一个 SQL in 子句,其中包含您可能想要匹配的区域中的所有项目。
a. It looks like you have a typo here:
but the main problem is
b. I'm guessing you're using Linq to Entities but its not clear. In any case what is happening is that the query builder is trying to turn that 'areas.Any(...)' into SQL and it can't do it because areas is not an IQueryable from your database, but a local variable. I suggest you use something like this WhereIn custom Linq operator as described here or here. That will build a SQL in clause containing all the items in areas that you might want to match against.