4thSpace
4thSpace

Reputation: 44352

Comparing date parts in LINQ

In LINQ to SQL, how do I compare only the date part of an sql datetime column and .net datetime object?

Upvotes: 3

Views: 2928

Answers (5)

Toolkit
Toolkit

Reputation: 11129

using System.Data.Entity;

DbFunctions.TruncateTime(u.BirthDate) = DbFunctions.TruncateTime(someDate)

Upvotes: 1

Ymagine First
Ymagine First

Reputation: 1204

using System.Data.Objects.SqlClient; //Don't forget this!!

//You can access to SQL DatePart function using something like this:

YourTable.Select(t => new { DayOfWeek = SqlFunctions.DatePart("weekday", t.dateTimeField) - 1 }); //Zero based in SQL

//You can compare to SQL DatePart function using something like this:

DateTime dateToCompare = DateTime.Today;
YourTable.Where(t => SqlFunctions.DatePart("weekday", t.dateTimeField) - 1 == dateToCompare }); //Zero based in SQL

Upvotes: 0

Frank Tzanabetis
Frank Tzanabetis

Reputation: 2836

You could create a CLR UDF to do the date only compare and then reference that in your linq to sql linq query.

Upvotes: 0

tvanfosson
tvanfosson

Reputation: 532765

Linq to SQL supports translation of the Date property to SQL for comparisons, etc. More information on the supported options can be found on MSDN.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1504172

Try using the Date property of both:

Date today = DateTime.Today; // Effectively DateTime.Now.Date

var dataFromToday = from record in context.Records
                    where record.TimeStamp.Date == today
                    select record;

I believe this works for LINQ to SQL... as tvanfosson says, it doesn't for EF.

Upvotes: 2

Related Questions