我有一张关于CustomerGroups和产品的折扣表。
密钥:
关系:
我有一个使用EF填充的变量Discounts1:
IQueryable<Models.Discount> Discounts1 = _entities.Discounts;
我想要的是要求所有折扣百分比的折扣,是没有联系的客户集团,并与某一特定的产品。
我尝试使用的linq表达式是:
var candidates = (from discount in Discounts1
where (discount.CustomerGroup == null)
&& discount.Products.Contains(product)
select discount.Percentage).ToList();
当我运行这段代码时,我得到的是一个带有消息的NotSupportedException
无法创建“Models.Product”类型的常量值。在此上下文中只支持基本类型或枚举类型。
我做错了什么?
发布于 2013-08-08 07:03:34
实体框架无法将Contains(product)
转换为SQL代码。你的问题在于:
discount.Products.Contains(product)
您应该通过它的ProductID
来搜索产品,这应该是一个基本类型。
这是一个已知的问题,记录在这里:引用不支持的非标量变量
不支持在查询中引用非标量变量(例如实体)。当执行这种查询时,会抛出一个NotSupportedException异常,其中的消息声明“无法创建EntityType类型的常量值。在此上下文中只支持基本类型(例如Int32、String和Guid')”。
发布于 2013-08-08 07:11:52
Contains
会破坏非原语类型,尽管您可以用一种更简单的方式重写查询以避免它(假设Product
有一个原始ProductId
列)
from d in Discounts1
from p in d.Products
where d.CustomerGroup == null && p.ProductId == product.ProductId
select d.Percentage
发布于 2013-08-08 07:14:02
这是一个解决办法,亚历克斯是第一个回答的,所以我标记他为解决者。
var candidates = (from discount in Discounts1
where (discount.CustomerGroup == null)
&& discount.Products.Any(p=>p.ProductID == product.ProductID)
select discount.Percentage).ToList();
https://stackoverflow.com/questions/18119799
复制相似问题