56

Please help. I am trying to figure out how to use DATE or DATETIME for comparison in a linq query.

Example: If I wanted all Employee names for those who started before today, I would do something like this in SQL:

SELECT EmployeeNameColumn
FROM EmployeeTable
WHERE StartDateColumn.Date <= GETDATE() //Today

But what about linq?

DateTime startDT = //Today

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

The above WHERE doesn't work:

Exception Details: System.NotSupportedException: The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

abatishchev
  • 98,240
  • 88
  • 296
  • 433

11 Answers11

90

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/

dubonzi
  • 1,492
  • 1
  • 21
  • 31
Mandeep Janjua
  • 15,583
  • 4
  • 29
  • 24
  • Was struggling with this, decided to use an extension method, just to find later on about this -.- – Andrei Dvoynos Nov 02 '12 at 18:10
  • 6
    This should have been the answer – Mr. 笑哥 Apr 09 '13 at 07:14
  • 3
    EntityFunctions was obsoleted, replaced by DbFunctions, updated answer to reflect this – Chris Marisic May 21 '14 at 19:48
  • 2
    EntityFunctions was replaced in EF 6.0. So if you're still on 4.5 or earlier (like myself) you should still use EntityFunctions. – mikesigs Jan 07 '15 at 16:32
  • 3
    how you seen what sql query is DbFunctions.TruncateTime generating: ((convert (datetime2, convert(varchar(255), [Extent1].[InspectionReportInfo_Date], 102), 102)) = '2015-02-10T00:00:00' this kills any index and I would avoid it... https://social.msdn.microsoft.com/Forums/en-US/45f496e1-550d-4638-9673-127e406e2352/entityfunctions-truncatetime-inefficiency?forum=adodotnetentityframework&prof=required – pajics Jun 18 '15 at 21:57
  • Agree. This should have been the answer – Rolwin Crasta Feb 23 '16 at 09:08
21

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.

jason
  • 236,483
  • 35
  • 423
  • 525
  • 1
    This worked: WHERE StartDateColumn <= GETDATE() //Today This did not: WHERE StartDateColumn.Date <= GETDATE() //Today I had .Date in my statement - I must have been over thinking the issue. Thank you. kam –  Jul 06 '09 at 17:34
  • 6
    This is not the problem - e.AsofDate.Date is the problem (compare only the date portion - on both sides... – Dani Jan 17 '11 at 10:50
10

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 
Chuck Norris
  • 15,207
  • 15
  • 92
  • 123
Shiraz Bhaiji
  • 64,065
  • 34
  • 143
  • 252
8

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...

Martin Buberl
  • 45,844
  • 25
  • 100
  • 144
Ejaz
  • 91
  • 1
  • 2
6

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();
abatishchev
  • 98,240
  • 88
  • 296
  • 433
2

I'm curious to the error message saying 'Date', when you're passing a 'DateTime'. Could it be that 'StartDateColumn' is actually a 'Date', rather than a 'DateTime' in the database? That might mess up the comparison...

Suraj Shrestha
  • 1,790
  • 1
  • 25
  • 51
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
2

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") ;
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Yousuf Qureshi
  • 498
  • 2
  • 7
  • 21
1

I am using a LinqDataSource and I had problems getting my query with a Date Comparison in it to execute without errors. The answer is to use the WhereAddParameters function and add the test value as a strongly typed parameter.

See the example below where I am matching a groupid and checking to see if the StopDate in my record is greater that or equal to a Date/Time stamp of now.

I am using this code fragment currently and it works like a charm.

LinqCampaigns.WhereParameters.Add("StopDate", System.Data.DbType.Date, DateTime.Now.ToString())
LinqCampaigns.Where = "GroupId = " & myGrp & " &&  " & "StopDate >= @StopDate"

Works like a charm....

Martin Buberl
  • 45,844
  • 25
  • 100
  • 144
Les
  • 11
  • 2
1

use a local variable to store the Date value and then use that variable in the query:

DateTime today = DateTime.Now.Date; from scheme in context.schemes where scheme.EndDate > today select scheme

Niraj
  • 1,782
  • 1
  • 22
  • 32
0

.Date did not work, but .Day did for me.

var query = from o in Payments
    where o.Order.OrderDate.Day != o.PaymentDate.Day
    orderby o.Order.OrderDate
    select new
    {
     o.Order.OrderID,
     o.Order.OrderDate,
     o.PaymentDate,      
     o.Order.FirstName,
     o.Order.LastName,
     o.Order.CustomerID
    };


query.Dump();
jonsca
  • 10,218
  • 26
  • 54
  • 62
ADBatBWD
  • 9
  • 1
  • 1
    This is probably ***not*** what you want. It will simply get the Day of the Month. So, for instance, Jan 01 & Feb 01 both have the same 'Day' component value, despite actually being different days in real time. – JoeBrockhaus Aug 31 '15 at 20:00
-1

ensure that you check null value like this :

 '(from mm in _db.Calls 
   where mm.Professionnal.ID.Equals(proid)
   && mm.ComposedDate.HasValue &&
   (mm.ComposedDate.Value >= datemin) && (mm.ComposedDate.Value <= date)
   select mm).ToArray();'