Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Linq query to compare date only with DateTime field

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;
like image 403
NealR Avatar asked Feb 08 '13 18:02

NealR


People also ask

How do I compare two dates in LINQ query with time?

Meeting dates are stored in this table using the following format: May 2nd 2011 is (for example) formatted as 5/2/2011 . My requirement is to get the meetings between two dates (say, 4/25/2011 and 5/2/2011) and to write a query comparing a date with these two dates. Does it compare like 4/25/2011 < 4/26/2011?

Can we compare date with DateTime in SQL?

The right way to compare date only values with a DateTime column is by using <= and > condition. This will ensure that you will get rows where date starts from midnight and ends before midnight e.g. dates starting with '00:00:00.000' and ends at "59:59:59.999".

How do I check if one date is greater than another in C#?

Compare() Method in C# This method is used to compare two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance. Syntax: public static int Compare (DateTime t1, DateTime t2);


1 Answers

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.

like image 196
صفي Avatar answered Sep 21 '22 17:09

صفي