在实体框架内格式化的条款

时间:2013-06-18 19:29:11

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

我在db上下文中有以下查询

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

2 个答案:

答案 0 :(得分: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之间,即午夜之日和第二天午夜之间。

答案 1 :(得分:0)

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

假设数据库中的.DateEntered值是Date类型(而不是DateTime),请尝试:

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