【问题标题】:Trying to Compare LINQ-to-Entity to Date Results in Error尝试将 LINQ-to-Entity 与日期进行比较会导致错误
【发布时间】:2011-03-14 17:08:31
【问题描述】:

我有一个简单的 If..Then 像这样:

  If rhcexists.First.SignatureDate > Date.Today.AddMonths(-6) Then
  End If

rhcexists 是对实体模型的简单查询:

Dim rhcexists = From p In dbContracts.Signatures _
                    Where p.StudentID = CStr(Session("people_code_id")) _
                    And p.ContractType = "rhc" _
                    Order By p.ID Descending _
                    Select p

问题是这种比较会导致错误:

LINQ to Entities 无法识别方法“System.Object get_Item(System.String)”方法,并且该方法无法转换为存储表达式。

这发生在 If 子句上。有什么想法为什么会发生这种情况以及我该如何解决?

我正在使用 ASP.NET 4、EF 4 和 VS 2010 SP1。

【问题讨论】:

    标签: asp.net vb.net entity-framework entity-framework-4


    【解决方案1】:

    问题出在您的查询中。在 if 语句中引发异常,因为查询的执行被推迟到需要运行时。问题出在

    Session("people_code_id")
    

    LINQ 查询中的所有内容都需要转换为 SQL 才能进行查询。实体框架无法将 Session Item getter 转换为 SQL,因此会引发异常。尝试在查询之前将其拉出到变量中,如下所示:

    Dim peopleCodeId = CStr(Session("people_code_id"))
    Dim rhcexists = From p In dbContracts.Signatures _
                        Where p.StudentID = peopleCodeId _
                        And p.ContractType = "rhc" _
                        Order By p.ID Descending _
                        Select p
    

    (我的 VB.NET 有点生疏,但我认为是对的)

    【讨论】:

      猜你喜欢
      • 2023-03-26
      • 1970-01-01
      • 2023-03-08
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-01
      相关资源
      最近更新 更多