【问题标题】:Trying to select distinct list of months from date where year = xxxx - linq to entities尝试从年份 = xxxx - linq 到实体的日期中选择不同的月份列表
【发布时间】:2016-07-15 01:59:18
【问题描述】:

我正在尝试从年份 = xxxx 的日期字段中选择不同的月份列表。我已经阅读了这个网站上的其他问题和答案,但似乎无法让我的工作。我正在使用实体框架和 linq 到实体 - 这是我最新的代码:

 Function BellMonthlySummaryMonthFiltering(years As Nullable(Of Integer), monthval As Nullable(Of Integer)) As JsonResult


        If Not years Is Nothing Then

            Dim listMonths As List(Of DateTime) = db.MobileBill_Summary.Where(Function(o) o.InvoiceDate.Year.Equals(years)).Select(Function(s) s.InvoiceDate.Month).Distinct.AsEnumerable.Select(Function(t) New DateTime(1999, t, 1)).ToList
        End If

        'Return Json(months, JsonRequestBehavior.AllowGet)

    End Function

这是我得到的错误:

附加信息:无法创建“System.Object”类型的常量值。此上下文仅支持原始类型或枚举类型。我按照本文中的说明进行操作:

Linq to entities distinct year from datetime column

【问题讨论】:

  • 让我们开始分解这个查询 - 即“开始删除废话,直到它工作!”。您介意在第一次选择之后 - 在不同之前尝试吗?
  • 好的,我将代码更改为: Dim listMonths As List(Of Integer) = db.MobileBill_Summary.Where(Function(o) o.InvoiceDate.Year.Equals(years)).Select(Function (s) s.InvoiceDate.Month).ToList 仍然出现同样的错误
  • 好的,去掉第一个选择。你应该看看我要去哪里。可能是您的o.InvoiceDate.Year.Equals(years)。也许改用= 可能会修复它。这是因为它试图将其转换为 SQL。在早期的 LINQ 中,我们有内置的日期辅助函数。
  • 我刚刚注意到年份可以为空....使用years.Value。如果您也想与 null 进行比较,请使用第二个比较运算符 - o.InvoiceDate.Year = Nothing Or o.InvoiceDate.Year = years.Value(如果我的 vb 错误,请见谅)。
  • 你是救世主 - 改成 = 成功了!从来没有想过。最终代码是: Dim listMonths As List(Of String) = db.MobileBill_Summary.Where(Function(o) o.InvoiceDate.Year = years).Select(Function(s) s.InvoiceDate.Month).Distinct.AsEnumerable.Select (Function(t) New String(MonthName(t))).ToList - 获取月份名称列表

标签: asp.net-mvc entity-framework


【解决方案1】:

将 where 子句更改为:

Where(Function(o) o.InvoiceDate.Year = years)

这是由于 EF 如何将其转换为 SQL。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多