【问题标题】:Formatting within Entity Framework Where Clause在实体框架 Where 子句中格式化
【发布时间】:2013-06-18 19:29:10
【问题描述】:

我的数据库上下文有以下查询

Dim query = (
    From n In db.tblNews
    Join nc In db.tblNewsCategories On n.CatID Equals nc.CategoryID
    Order By n.DateEntered Descending
    Select New With {
      .NewsID = n.NewsID,
      .Title = n.Title,
      .NewsText = n.NewsText,
      .isPublished = n.isPublished,
      .CatID = n.CatID,
      .CategoryName = nc.CategoryName,
      .DateEntered = n.DateEntered,
      .ReadCount = n.ReadCount,
      .DatePublished = n.DatePublish
       }
    )

然后,根据我的 DropDownListBox 中的值,我在后面的代码中应用 WHERE 子句过滤数据,例如;

If sDate <> "" Then
    query = query.Where(Function(n) n.DateEntered = sDate)
End If

现在,sDate 的格式为2013-06-18,而在数据库中,对应的DateTime 字段的格式为2013-06-18 16:41:33.973,因此,查询返回零结果。

我已尝试执行以下操作:

If sDate <> "" Then
    query = query.Where(Function(n) String.Format(n.DateEntered, {0:yyyy-MM-dd}) = sDate)
End If

这给了我错误: LINQ to Entities 无法识别方法 'System.String ToString(System.String)' 方法,并且该方法无法转换为存储表达式

我也不想在我的选择中格式化日期,因为我希望输出与数据库完全相同。

如何在查询的 where 子句中格式化日期?如果我不能解决这个问题?

【问题讨论】:

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


    【解决方案1】:

    试试:

    Dim dateStart = DateTime.Parse(sDate)
    Dim dateEnd = date.AddDays(1)
    query = query.Where(Function(n) n.DateEntered >= dateStart And n.DateEntered < dateEnd)
    

    基本上,这将检查DateEntered 是否介于sDate(即午夜的日期)和第二天的午夜之间。

    【讨论】:

    • 这不太理想,因为它需要 2 次比较。
    • 如果您将裸日期与日期/时间进行比较,我认为您必须使用 LINQ 以这种方式进行。
    • 您应该仍然能够获取 DateTime 的 Date 部分并将其与日期进行比较。在 .Net 中,Date 本质上是一个 DateTime,它的 Time 部分具有默认值。
    【解决方案2】:

    您必须更改 sDate 变量的格式(或至少以新格式复制它)并将其与 LINQ 查询中的内容进行比较。 LINQ 不理解 .ToString,您正在尝试将 String 值与 Date 或 DateTime 值进行比较。 VB 对隐藏这种东西真的很不好,所以你真的不知道自己做错了什么。

    假设您的数据库中的 .DateEntered 值是日期类型(而不是日期时间),试试这个:

    If Not String.IsNullOrWhiteSpace(sDate) Then
        Dim someDate As Date = DateTime.Parse(sDate).Date
        query = query.Where(Function(n) n.DateEntered = someDate)
    End If
    

    编辑:如果是 DateTime,试试这个

    If Not String.IsNullOrWhiteSpace(sDate) Then
        Dim someDate As Date = DateTime.Parse(sDate).Date
        query = query.Where(Function(n) n.DateEntered.Date = someDate)
    End If
    

    【讨论】:

    • 感谢@Douglas,但日期值属于 DateTime2 数据类型。否则,我不会有相等操作的问题(我猜?)。
    • 现在试试,如果它有效,请告诉我。只要数据库中的 DateTime 值不可为空,我所做的编辑就会起作用。如果是,则需要将它们与 n.DateEntered.Value.Date 进行比较。
    猜你喜欢
    • 2011-10-21
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-13
    相关资源
    最近更新 更多