【问题标题】:How to compare date in Entity Framework?如何在实体框架中比较日期?
【发布时间】:2017-12-24 15:07:48
【问题描述】:

我想比较实体框架中的日期、日期时间字段。在我的数据库中,我有一列StartTimedatesmalldatetime。好的,我用这种情况

var list = db.tmpListAction.Where(e => e.StartTime.ToString() == "2017-12-15").ToList();

它不工作。它返回null,尽管我在表中有数据。

【问题讨论】:

标签: c# sql entity-framework linq


【解决方案1】:

为什么还要再转换成字符串??这很可能会破坏您的代码,因为 .ToString() 不能保证返回您期望的数据表示。

只需将日期保留为日期并像这样进行比较:

DateTime desiredDate = new DateTime(2017, 12, 15);
var list = db.tmpListAction.Where(e => e.StartTime == desiredDate).ToList();

【讨论】:

  • 亲爱的@marc_s,正如你在我的例子中看到的,我想将它作为一个字符串进行比较,所以我尝试使用"2017-12-15",我很困惑我喜欢使用字符串。
  • @Brian Crist,您为什么坚持将日期作为字符串进行比较?这不是正确的方法。
猜你喜欢
  • 2021-10-24
  • 1970-01-01
  • 1970-01-01
  • 2017-10-23
  • 1970-01-01
  • 2016-03-07
  • 1970-01-01
  • 2014-11-01
  • 2018-05-14
相关资源
最近更新 更多