Comparing date parts in LINQ
在LINQ to SQL中,如何仅比较sql datetime列的日期部分和.net datetime对象?
尝试同时使用两者的
1 2 3 4 5 | 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 2 3 | using System.Data.Entity; DbFunctions.TruncateTime(u.BirthDate) = DbFunctions.TruncateTime(someDate) |
Linq to SQL支持将Date属性转换为SQL以进行比较等。有关受支持的选项的更多信息,可以在MSDN上找到。
1 2 3 4 5 6 7 8 9 10 | 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 |
您可以创建CLR UDF以仅比较日期,然后在linq中将其引用到sql linq查询。