![](/img/trans.png)
[英]Only primitive types ('such as Int32, String, and Guid') are supported in this context
[英]Linq, array.Contains() generating exception: Only primitive types ('such as Int32, String, and Guid') are supported in this context
我正在尝试使用Linq执行查询,这是我的新手。 我想收到一系列ID并检索带有这些ID的产品。 我得到的linq查询就是这个:
public Product[] RetrieveProduct(int[] ids)
{
var query = from productInfos in productRepository.Table
where (ids.Contains(productInfos.Id))
&& productInfos.Active
select new ProductIndiInfo
{
ProductId = productInfos.Id,
CurrentPrice = productInfos.CurrentPrice
};
return query.ToArray();
}
但我一直收到着名的例外:
{“无法创建类型'System.Int32 []'的常量值。在此上下文中仅支持基本类型(例如Int32,String和Guid')。”}
我读过的一些资源说它不可用。 但其他一些人告诉我它应该有效。 我在这里和博客中看过很多有替代品的帖子,但是它不起作用。 我开始认为这是一个语法问题......
我也试过这种方法:
var query = from productInfos in pricingInfoRepository.Table
where ids.Any(id => id == productInfos.ProductId)
&& productInfos.Active
select new PricingInfo
{
ProductId = productInfos.Id,
CurrentPrice = productInfos.CurrentPrice
};
return query.ToArray();
但我遇到了同样的问题。
有人可以告诉我,如果我的语法错误或者它是否真的是Linq问题? (不支持操作?)
如何找出我使用的EF版本?
更新:据我所知,关于ids.Contains()的这个问题将是一个L2S问题,但可能的答案是EF2不支持它。 我理解正确吗?
假设pricingInfoRepository
是您的对象上下文或返回相关对象集的存储库类,这可能会起作用(它是查询的方法语法版本,稍微调整一下):
var query = pricingInfoRepository.Table
.Where(pi => pi.Active && ids.Contains(pi.Id))
.Select(pi => new PricingInfo
{
ProductId = pi.Id,
CurrentPrice = pi.CurrentPrice
})
.ToArray();
你在一个int
数组上调用Contains()
,LINQ将其视为IEnumerable
,应该没问题。 我之前使用过与此类似的查询,没有任何问题......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.