Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to compare Dates in DateTime attribute using Entity Framework 4 and Linq queries

I'm trying to run the following bit of code, but the comparison fails by not handing my the entities I expect it to.

It's comparing 06/09/2011 0:00:00 to 06/09/2011 12:25:00, the latter being my databases record value. So that's why the comparison is failing and I'm not getting the records I need.

I'm just trying to compare if the dates match up, I'm don't care about the time.

DateTime today = DateTime.Now.Date;
var newAuctionsResults = repo.FindAllAuctions()
                        .Where(a => a.IsActive == true || a.StartTime.Value == today)
                        .ToList();

How can I compare only the dates?

If use the .Date property in the .StartTime.Value part, I get an exception:

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

like image 713
Only Bolivian Here Avatar asked Sep 06 '11 13:09

Only Bolivian Here


People also ask

Can we use LINQ with entity Framework?

So, we can use LINQ for querying against DbSet , which will be converted to an SQL query. EF API executes this SQL query to the underlying database, gets the flat result set, converts it into appropriate entity objects and returns it as a query result.

What is EF LINQ?

LINQ allows you to use C# (or your . NET language of choice) to write strongly typed queries. It uses your derived context and entity classes to reference database objects. EF Core passes a representation of the LINQ query to the database provider.


2 Answers

You can use the individual members:

var newAuctionsResults = repo.FindAllAuctions()
                        .Where(a => a.IsActive == true 
                                    || (a.StartTime.Value.Year == todayYear
                                        && a.StartTime.Value.Month == todayMonth
                                        && a.StartTime.Value.Day == todayDay))
                        .ToList();

...or use any of the other methods/properties supported in L2E.

like image 188
Craig Stuntz Avatar answered Sep 24 '22 07:09

Craig Stuntz


You can also 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.

like image 26
صفي Avatar answered Sep 22 '22 07:09

صفي