0

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

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,在 db 中,相应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 子句中格式化日期?如果我不能解决这个问题吗?

4

2 回答 2

0

您将不得不更改 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
于 2013-06-18T20:01:21.087 回答
0

尝试:

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

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

于 2013-06-18T19:33:12.800 回答