Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I perform Date Comparison in EF query?

People also ask

How do you compare two dates in a query?

Here we will see, SQL Query to compare two dates. This can be easily done using equals to(=), less than(<), and greater than(>) operators. In SQL, the date value has DATE datatype which accepts date in 'yyyy-mm-dd' format. To compare two dates, we will declare two dates and compare them using the IF-ELSE statement.

Can you use comparison operators on dates in SQL?

We can compare dates using Comparison Operators in SQL like, = (Equals), < (Less than), > (Greater than), <= (Less than Equal), >= (Greater than Equal), <> (Not Equal), etc.


Use the class DbFunctions for trimming the time portion.

using System.Data.Entity;

var bla = (from log in context.Contacts
           where DbFunctions.TruncateTime(log.ModifiedDate) 
                              ==  DbFunctions.TruncateTime(today.Date)
           select log).FirstOrDefault();

Source: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/84d4e18b-7545-419b-9826-53ff1a0e2a62/


That should work. Are you sure that there isn't another part of the query that triggered the exception? I have several instances of queries of the form

var query = from e in db.MyTable
            where e.AsOfDate <= DateTime.Now.Date
            select e;

in my code.


It may be due to the date in the database being nullable. Try this:

var EmployeeName =
from e in db.employee
where e.StartDateColumn.Value <= startDT 

You can check the condition like this

var nextDay = DateTime.Today.AddDays(1);

var query = from e in db.MyTable
            where e.AsOfDate >= DateTime.Today && e.AsOfDate < nextDay 
            select e;

here you'll get the records on AsOfDate date as we checking between today(00:00:00) and tommorow(00:00:00) we'll get today's date record only what ever may be the time...


You can not use .Date

If you would like to check for today you can create a datetime with no time

DateTime myDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
var e = (from mds in myEntities.Table
         where mds.CreateDateTime >= myDate
         select mds).FirstOrDefault();

try this:

DateTime dd = DateTime.Parse("08/13/2010 00:00:00");
var data = from n in ContributionEligibilities
           where n.ModifiedDateTime.Date >= DateTime.Parse("08/13/2010").Date
           select n; 
data.Dump("Result") ;