In LINQ to SQL, how do I compare only the date part of an sql datetime column and .net datetime object?
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.
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.
You could create a CLR UDF to do the date only compare and then reference that in your linq to sql linq query.
using System.Data.Entity;
DbFunctions.TruncateTime(u.BirthDate) = DbFunctions.TruncateTime(someDate)
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
.Date
property on the DateTime for the comparison. -- just checked, it does. Link posted in my answer. - tvanfosson