我需要将一个对象与我传入的参数进行比较。逻辑是:
- 如果
territory == null
。返回所有订单
- 如果
territory != null
并且 Orders 中的Territory
实体是!= null
。返回匹配两个实体的Id
属性 (PK) 的Orders
。
我有以下 LINQ 语句:
我的方法的简化版本是(WHERE
子句中通常还有其他过滤器):
public void Execute(Territory territory)
{
using (var context = DatabaseHelper.CreateContext())
{
var orders = context.Orders.Where(x =>
(
(territory == null) ||
(x.Territory != null && x.Territory.Id == territory.Id)
)
);
if (!orders.Any()) //Exception occurs here on materialising the query
{
//Do something
}
}
}
我收到异常 NotSupportedException
和消息:
Unable to create a constant value of type 'ENTITY'. Only primitive types or enumeration types are supported in this context.
虽然我理解错误,因为我没有传递原始类型。如何更改 LINQ 查询以使其返回预期结果?
最佳答案
试试这个:
var t = territory == null;
var orders = context.Orders.Where(x =>
t || (x.Territory != null && x.Territory.Id == territory.Id));
这背后的原因是它试图将 territory
转换为 SQL 查询中的常量,但当然 territory
不是原始类型或服务器上的任何等效类型,因此它会抛出异常(exception)。但是,您可以在外部缓存常量 bool 值(但仍在检查 territory
的有效范围内)并在查询中使用该常量。
关于c# - Entity Framework - Linq - 比较可空对象 - NotSupportedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32742030/