简体   繁体   English

如果修改日期大于或现在使用linq,则从数据库中选择所有记录

[英]Select all records from a db if there modified date is greater or now using linq

I am having an issue, that I am wondering can anyone help me with. 我有一个问题,我想知道有人可以帮助我吗。 I am creating a list from a Database using Linq, I want to return all the records in a list that have been Modified on the current day. 我正在使用Linq从数据库创建列表,我想返回列表中当天已修改的所有记录。

The date was intaily set by: 日期由以下日期确定:

  contact.CreatedDate = System.DateTime.Now; ctx.Contacts.Add(contact);' 

When the record is updated the ModifiedDate is given a value. 记录更新时,会给ModifiedDate一个值。

  contact.ModifiedDate = System.DateTime.Now;
  ctx.Entry(contact).State = EntityState.Modified;

Which is all fine the issue is below: 很好,问题在下面:

var Contactlist = ctx.Contacts.Where(x => x.ModifiedDate = System.DateTime.Now ).ToList();

For Entity framework EntityFunctions.TruncateTime 对于实体框架EntityFunctions.TruncateTime

var Contactlist = ctx.Contacts.Where(x => 
                       EntityFunctions.TruncateTime(x.ModifiedDate) == EntityFunctions.TruncateTime(System.DateTime.Today))
                       .ToList();

For LINQ to objects you could have compare the Date part only like: 对于LINQ与对象,您可以只比较Date部分,例如:

var Contactlist = ctx.Contacts.Where(x => x.ModifiedDate.Date == System.DateTime.Today)
                              .ToList();

DateTime type object in .Net framework has Date as well as Time part, your current check would compare both date and time. .Net框架中的DateTime类型对象具有DateTime部分,您当前的检查将比较日期和时间。 (Also you need == instead of = ) (此外,您需要==而不是=

DateTime.Now would return current date with current time, DateTime.Today will return your current date with time set to 00:00:00 . DateTime.Now将返回当前日期和当前时间, DateTime.Today将返回您的当前日期,时间设置为00:00:00 Similarly DateTime.Date would return the date part with time set to 00:00:00 , so you can use that for comparing date part only. 同样, DateTime.Date将返回日期部分,并将时间设置为00:00:00 ,因此您可以将其仅用于比较日期部分。

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

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