c# - Entity Framework - Linq - 比较可空对象 - NotSupportedException

标签 c# entity-framework linq linq-to-entities

我需要将一个对象与我传​​入的参数进行比较。逻辑是:

  • 如果 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/

相关文章:

entity-framework - 数据库设计 : more tables vs less tables

c# - 如何将带有where子句的多个SQL LEFT JOIN语句转换为LINQ

c# - 在 SQL CLR UDF 中使用 System.Linq 程序集

C# 异步 Ping : How to avoid an out of memory exception?

c# - URI 前缀无法识别 OnDownloadStringCompleted

c# - Task.Delay 会导致线程切换吗?

java - 实体重复

c# - 使用 TokenLookUpEdit 的 SelectedItems 填充 WPF Datagrid

security - Entity Framework 安全和注入(inject)

c# - 以已知类作为分组键的 GroupBy