【问题标题】:how to convert string to datetime in Linq where clause如何在Linq where子句中将字符串转换为日期时间
【发布时间】:2018-03-30 15:43:52
【问题描述】:
DateTime newDate = DateTime.Now.AddDays(-30);

var queryResultPage = (from r in CustomPlanning
                       where (r.Assignment == "In Use") && 
                             (r.CUST_SHRT_NM != null) && 
                              System.Convert.ToDateTime(r.lastlogontimestamp) < newDate && 
                             !(from uA in SurveyActivity                                                                                                                                                                  
                               where uA.CustomDemandID == r.ID
                               select uA.CustomDemandID).Contains(r.ID)
                       select r)
                       .OrderBy(t => t.ID);

以上是我的代码。 lastlogontimestamp 是我表中的一个字符串字段。我需要执行此检查以在网格中显示查询结果。有人可以帮忙吗?

【问题讨论】:

  • 首先,当你使用你的代码时,一定要解释清楚出了什么问题。第二,你不能只比较r.lastlogontimestamp &lt; newDate吗?当你尝试时会发生什么?
  • 数据库中存储的日期格式是什么?请提供样本数据。
  • EF 不支持从字符串转换为日期时间。你为什么首先将日期作为 varchar 存储在数据库中?将来它会给你带来其他的麻烦。
  • r.lastlogontimestamp 是日期时间还是字符串。常见的错误是获取 DateTime 并尝试将其转换为 DateTime。它不起作用。
  • 很好的实际例子,为什么人们应该思考如何在数据库中存储东西,并选择正确的类型来存储东西。

标签: c# linq asp.net-mvc-4 linq-to-sql linq-to-entities


【解决方案1】:

好的,我试过了,它成功了

DateTime newDate = DateTime.Now.AddDays(-30);

var queryResultPage = (from r in CustomPlanning
                       where (r.Assignment == "In Use") && (r.lastlogontimestamp != null && r.lastlogontimestamp != string.Empty) 
                       &&  (r.CUST_SHRT_NM != null) 
                       && !(from uA in SurveyActivity where uA.CustomDemandID == r.ID select uA.CustomDemandID).Contains(r.ID)
                       select r).OrderBy(t => t.ID).ToList();
queryResultPage = queryResultPage.Where(r => System.Convert.ToDateTime(r.lastlogontimestamp) < newDate).ToList();

【讨论】:

  • 将数据物化到内存中允许您使用支持所有 C# 的 LINQ To Objects。请注意,如果lastlogontimestamp 的格式非常固定,您可以使用DbFunctions.CreateDateTime 并构建转换。
【解决方案2】:

您不能直接在此查询中。您需要在列表中具体化查询的结果,然后运行另一个查询以使用 Linq-To-Objects 过滤返回的 CustomPlanning(它支持转换)。

您可以将 newDate 转换为字符串

string newDate = DateTime.Now.AddDays(-30).ToString();

并尝试比较字符串,但是您需要涵盖很多很多情况,因此不建议这样做。可以考虑将lastlogontimestamp的类型改为DateTime,当有日期时,很自然的将它们存储为日期。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多