Use Linq query to compare date only with DateTime field
Asked Answered
H

9

10

I need to compare just the date only in a Linq query that involves a datetime field. However, the syntax below results in the following error message

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

Does anyone know how to extract just the date out of a datetime field?

var duplicate = from a in _db.AgentProductTraining
                where a.CourseCode == course.CourseCode &&
                a.DateTaken.Date == course.DateTaken.Date &&
                a.SymNumber == symNumber
                select a;
Henna answered 8/2, 2013 at 18:11 Comment(0)
P
15

It might seem a little roundabout, but you can use the SqlFunctions class' DateDiff method for doing this. Just pass in both values and use "Day" for finding the difference between them in days (which should be 0 if they are on the same day).

Like the following:

from a in _db.AgentProductTraining
                where a.CourseCode == course.CourseCode &&
                SqlFunctions.DateDiff("DAY", a.DateTaken, course.DateTaken) == 0 &&
                a.SymNumber == symNumber
                select a;
Penelopa answered 8/2, 2013 at 18:19 Comment(5)
Wouldn't the diff be zero if the dates are on different dates, but are spaced at less than one day, say, Jan-5, 2013 23:30:00 and Jan-6, 2013 01:30:00?Veridical
Unfortunately this did not work either. Since it's nested in the Linq query, I'm looking into finding out why but not having any luck...Henna
Did it still throw that exception?Penelopa
System.NotSupportedException: This function can only be invoked from LINQ to Entities.Exaggerated
@UsmanKhalid That is correct: You can only use this method with a LINQ to Entities call. Judging by the fact that there is an object called _db I assume that this question has to do with such a query.Penelopa
T
13

You can use EntityFunctions.TruncateTime() under the namespace System.Data.Objects

Ex.

db.Orders.Where(i => EntityFunctions.TruncateTime(i.OrderFinishDate) == EntityFunctions.TruncateTime(dtBillDate) && i.Status == "B")

Works like charm.

UPDATE

This function works only when you querying entities through LINQ. Do not use in LINQ-Object.

For EF6 use DbFunctions.TruncateTime() under System.Data.Entity namespace.

Tilly answered 5/12, 2013 at 9:52 Comment(5)
Hey @AlexAngas, you can check to verify this is working in EF4. which version are you using?Conciliar
I used EF5 and got this exception: System.NotSupportedException: This function can only be invoked from LINQ to Entities. at System.Data.Objects.EntityFunctions.TruncateTime(Nullable1 dateValue)`. Is there something i'm missing?Coppage
@AlexAngas This function works only when you querying entities through LINQ. Do not use in LINQ-Object.Conciliar
Dear down-voter, no offence in down-voting. But please comment what was missing / can be potentially improved, otherwise it spoils the reputation of the question that might be useful to someone in need.Conciliar
EntityFunctions is deprecated in EF6, DbFunctions should be used instead.Compose
G
6

You can do it like bellow:

var data1 = context.t_quoted_value.Where(x => x.region_name == "Pakistan" 
                        && x.price_date.Value.Year == dt.Year
                        && x.price_date.Value.Month == dt.Month
                        && x.price_date.Value.Day == dt.Day).ToList();
Granulose answered 24/6, 2014 at 6:46 Comment(0)
F
3

you must use System.Data.Entity.DbFunctions.TruncateTime

Fluorine answered 21/8, 2016 at 19:42 Comment(0)
C
2

try this

DateTime dt =course.DateTaken.Date;
var duplicate = from a in _db.AgentProductTraining
                where a.CourseCode == course.CourseCode &&
                a.DateTaken == dt &&
                a.SymNumber == symNumber
                select a;

if a.DateTaken contains Time also, then refer these links to modify your date.
The Date property cannot be used in LINQ To Entities.

Compare Dates using LINQ to Entities (Entity Framework)

'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported

http://forums.asp.net/t/1793337.aspx/1

Crissie answered 1/7, 2013 at 5:42 Comment(0)
H
0

This is how I ended by doing a similar Date search which I had to consider time (Hour and Minutes portion) also

from x in _db.AgentProductTraining
                where 
                       x.CreatedOn.Year == mydacourse.DateTakente.Year
                    && x.CreatedOn.Month == course.DateTaken.Month
                    && x.CreatedOn.Day == course.DateTaken.Day
                    && x.CreatedOn.Hour == course.DateTaken.Hour
                    && x.CreatedOn.Minute == course.DateTaken.Minute
                select x;
Humic answered 15/4, 2018 at 19:4 Comment(0)
S
0

Hey when I was building a query this below worked

                    DateTime date = Convert.ToDateTime(SearchText); 
                    query = query.Where(x => x.Date.Month == date.Month
                                          && x.Date.Day == date.Day
                                          && x.Date.Year == date.Year);

// Let me know if this worked for you as it pulled the date that was searched for me

Sholokhov answered 8/9, 2022 at 21:47 Comment(1)
you can just do x.Date == date.Date or x.Date.Equals(date.Date)Indus
I
0

A little bit ugly but it works as expected without using any sql functions:

var sessions = await Db.Set<Sessions>()
    .Where(x => x.Timetable == form.TimetableId)
    .Where(x => x.DateAndTimeOfSession >= form.BookingDate.Date) // <--
    .Where(x => x.DateAndTimeOfSession < form.BookingDate.Date.AddDays(1)) // <--
    .ToListAsync();
Impertinent answered 5/4, 2023 at 10:45 Comment(0)
N
-1

Take off the .Date If the field is a DateTime it can be compared with ==

var duplicate = from a in _db.AgentProductTraining
                where a.CourseCode == course.CourseCode &&
                a.DateTaken == course.DateTaken &&
                a.SymNumber == symNumber
                select a;
Noxious answered 11/4, 2015 at 18:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.