Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write LINQ to SQL query for getting today date records?

Tags:

c#

linq-to-sql

I want to get the today entered records using LINQ to SQL. I wrote the below code but it is returning previous date records also.

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 });

Can you please tell me how to get the today entered records only using LINQ to SQL?

like image 607
Sravanti Avatar asked Mar 29 '13 05:03

Sravanti


People also ask

How do I get the LINQ query in SQL?

You can get same generated SQL query manually by calling ToString: string sql = committeeMember. ToString(); This overridden method internally calls ObjectQuery.

How do you update a record in LINQ?

You can update rows in a database by modifying member values of the objects associated with the LINQ to SQL Table<TEntity> collection and then submitting the changes to the database. LINQ to SQL translates your changes into the appropriate SQL UPDATE commands.


1 Answers

Insetad of DateTime.Now use DateTime.Today like:

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 });

or You can try the following simpler version, (I am not sure if that would translate into 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 });
like image 124
Habib Avatar answered Nov 08 '22 13:11

Habib