Linq where clause compare only date value without time value

c# compare datetime entity-framework linq-to-entities

Question

var _My_ResetSet_Array = _DB
    .tbl_MyTable
    .Where(x => x.Active == true
        && x.DateTimeValueColumn <= DateTime.Now)
    .Select(x => x);

Upper query is working correct.
But I want to check only date value only.
But upper query check date + time value.

In traditional mssql, I could write query like below.

SELECT * FROM dbo.tbl_MyTable
WHERE 
CAST(CONVERT(CHAR(10), DateTimeValueColumn, 102) AS DATE) <= 
            CAST(CONVERT(CHAR(10),GETDATE(),102) AS DATE)
AND
Active = 1

So could anyone give me suggestion how could I check only date value in Linq.

1
54
11/23/2012 5:41:07 PM

Accepted Answer

There is also EntityFunctions.TruncateTime or DbFunctions.TruncateTime in EF 6.0

117
9/21/2019 10:00:57 AM

Popular Answer

Simple workaround to this problem to compare date part only

var _My_ResetSet_Array = _DB
                    .tbl_MyTable
                    .Where(x => x.Active == true && 
                               x.DateTimeValueColumn.Year == DateTime.Now.Year
                            && x.DateTimeValueColumn.Month == DateTime.Now.Month
                            && x.DateTimeValueColumn.Day == DateTime.Now.Day);

Because 'Date' datatype is not supported by linq to entity , where as Year, Month and Day are 'int' datatypes and are supported.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow