在LINQ to SQL中,如何仅比较sql datetime列和.net datetime对象的日期部分?
答案 0 :(得分:2)
尝试使用两者的Date
属性:
Date today = DateTime.Today; // Effectively DateTime.Now.Date
var dataFromToday = from record in context.Records
where record.TimeStamp.Date == today
select record;
我相信这适用于LINQ to SQL ...正如tvanfosson所说,它不适用于EF。
答案 1 :(得分:1)
Linq to SQL支持将Date属性转换为SQL进行比较等。有关支持选项的更多信息,请参见MSDN。
答案 2 :(得分:1)
using System.Data.Entity;
DbFunctions.TruncateTime(u.BirthDate) = DbFunctions.TruncateTime(someDate)
答案 3 :(得分:0)
你可以创建一个CLR UDF来比较日期,然后在你的linq中引用它到sql linq查询。
答案 4 :(得分:0)
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