简体   繁体   English

实体框架无法使用datetime.now条件返回数据库中的记录

[英]entityframework can't return the records in database with datetime.now condition

I am trying to return some records from the database using this query : 我试图使用此查询从数据库返回一些记录:

        ViewBag.TrafficEnter = _iTrafficRepository.Get().Where(i => i.Type == "ورود" && i.SubmitDateTime == DateTime.Now).ToList();

在此处输入图片说明

Here you can see my database records: 在这里您可以查看我的数据库记录:

在此处输入图片说明

But the problem is the query doesn't return any values .why ? 但是问题是查询不返回任何值。为什么?

Your comparing the DateTime values in your database with the value of DateTime.Now which returns the current time (including milliseconds) and could never match any of the values in the table. 您比较DateTime在你的数据库的价值值DateTime.Now返回当前时间(包括毫秒),可能永远不会匹配表中的任何值。

Modify you query to select values in a range 修改查询以选择范围内的值

var minDate = DateTime.Today; // returns today's with time component set to 00:00:00
var maxDate = minDate.AddDays(1);
ViewBag.TrafficEnter = _iTrafficRepository.Get()
    .Where(i => i.Type == "ورود" && i.SubmitDateTime >= minDate && i.SubmitDateTime < maxDate).ToList();

Assuming today's date is 24th May 2016, it will return all 17 records shown in your image. 假设今天的日期是2016年5月24日,它将返回图像中显示的所有17条记录。

The issue with DateTime.Now is that implies a very small date range that is equal to the smallest division of it's precision, in this case 1 millisecond. DateTime.Now的问题在于,它意味着一个非常小的日期范围,该范围等于其精度的最小分度,在这种情况下为1毫秒。 Unless your record is created with almost exactly the same value as DateTime.Now you'll never get a match. 除非您使用与DateTime几乎完全相同的值创建记录,否则您将永远不会获得匹配。

You have two solutions (that may not be appropriate to your needs); 您有两种解决方案(可能不适合您的需求);

Firstly rather than matching an exact dateTime, try to match a range eg 1 hour before/after DateTime.Now. 首先,与其匹配精确的dateTime,不如尝试匹配一个范围,例如,DateTime.Now之前/之后的1小时。 This would have the advantage of giving you control over range. 这样的好处是可以控制范围。

Alternatively you could try matching the date value (DateTime.Now.Date) with the date of your record. 或者,您可以尝试将日期值(DateTime.Now.Date)与记录的日期匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM