如何编写LINQ to SQL查询以获取今天的日期记录?

时间:2013-03-29 05:24:11

标签: c# linq-to-sql

我希望使用LINQ to SQL获取今天输入的记录。我写了下面的代码,但它也返回了以前的日期记录。

DateTime todaysDate = DateTime.Now;
DateTime yesterdaysDate = DateTime.Now.AddDays(-1);

var result = (from a in cxt.visitor.OrderByDescending(n => n.singin)
              where (a.singin > yesterdaysDate && a.singin <= todaysDate)
              select new {a.visitorid, a.visitorname, a.visitingperson, a.phonenumber, a.reasonforvisit, a.signature, a.singin });

请告诉我如何使用LINQ to SQL获取今天输入的记录?

1 个答案:

答案 0 :(得分:37)

而不是DateTime.Now使用DateTime.Today之类的:

DateTime startDateTime = DateTime.Today; //Today at 00:00:00
DateTime endDateTime = DateTime.Today.AddDays(1).AddTicks(-1); //Today at 23:59:59

var result = (from a in cxt.visitor.OrderByDescending(n => n.singin)
            where (a.singin >= startDateTime && a.singin <= endDateTime)
            select new {a.visitorid, a.visitorname, a.visitingperson, a.phonenumber, a.reasonforvisit, a.signature, a.singin });

或者您可以尝试以下更简单的版本,(我不确定这是否会转换为SQL)

var result = (from a in cxt.visitor.OrderByDescending(n => n.singin)
            where (a.singin.Date == DateTime.Today)
            select new {a.visitorid, a.visitorname, a.visitingperson, a.phonenumber, a.reasonforvisit, a.signature, a.singin });