如何在Linq查询中创建DateTime值?

时间:2013-10-07 22:58:41

标签: vb.net linq entity-framework

我正在尝试在Linq to Entities中创建一个查询。我希望它返回包含从我正在查询的表中的字符串派生的DateTime属性的对象。数据(在SQL Server中)有一个名为date_occurred的字符串日期字段(在数据库中显示为VARCHAR(8))。它有一个名为time_occurred的字符串时间字段(varchar(6))。

date_occurred的内容示例为“20131007”,代表2013年10月7日.time_occurred的内容示例为“145710”,表示下午2:57后的10秒。

我尝试了两种不起作用的方法:

Dim ATQuery = From e In EntityContext.vwSecAppAuditToday
   Order By e.date_occurred, e.time_occurred
   Select New AuditEntry With {
      .EventTime = DateTime.ParseExact(Trim(e.date_occurred) & Trim(e.time_occurred), "yyyyMMddHHmmss", CultureInfo.InvariantCulture),
      .ServerName = e.server_name
}

这会抛出一个NotSupportedException,并显示一条消息:“LINQ to Entities无法识别方法'System.DateTime ParseExact(System.String,System.String,System.IFormatProvider)'方法,而且此方法不能被翻译成商店表达。“

在此之前,我尝试过:

Dim ATQuery = From e In EntityContext.vwSecAppAuditToday
   Order By e.date_occurred, e.time_occurred
   Select New AuditEntry With {
      .EventTime = New DateTime(Integer.Parse(e.date_occurred.Substring(0, 4)),
         Integer.Parse(e.date_occurred.Substring(4, 2)),
         Integer.Parse(e.date_occurred.Substring(6, 2)),
         Integer.Parse(e.time_occurred.Substring(0, 2)),
         Integer.Parse(e.time_occurred.Substring(2, 2)),
         Integer.Parse(e.time_occurred.Substring(4, 2))),
      .ServerName = e.server_name
}

这也会引发NotSupportedException。在这种情况下,消息指出:“LINQ to Entities中仅支持无参数构造函数和初始值设定项。”

我正在尝试使用Linq to Entities做什么?

编辑:评论提醒

对于那些稍后阅读这篇文章的人,Moho和Matt Johnson做了特别有用的评论。我用+1标记了这些。

2 个答案:

答案 0 :(得分:2)

选择一个包含感兴趣字段的匿名类(称为投影),然后在枚举IQueryable后为每个项创建DateTime结构:

Dim ATQuery = From e In EntityContext.vwSecAppAuditToday
   Order By e.date_occurred, e.time_occurred
   Select New With {
      .DateOccurred = e.date_occurred,
      .TimeOccurred = e.time_occurred,
      .ServerName = e.server_name
}

Dim q2 = From e In ATQuery.ToArray()
         Select New AuditEntry With {
             .EventTime = DateTime.ParseExact(Trim(e.DateOccurred) & Trim(e.TimeOccurred), "yyyyMMddHHmmss", CultureInfo.InvariantCulture),
             .ServerName = e.ServerName
}

答案 1 :(得分:0)

您的新日期时间仅包含整数,因此看起来像20131008011300(2013/10/08 01:13:00)

/之间的日期,:之间的时间与日期和时间之间的space错过