![](/img/trans.png)
[英]Compare only date part from DateTime being aware of Timezone offset in C#?
[英]C# Linq compare only date from a datetime property
我对实体有以下Linq:
var details = Uow.EmployeeAttendances.GetAllReadOnly()
.Where(a => a.EmployeeId == summary.EmployeeId && a.Timestamp == summary.Date)
.ToList();
summary.Date
只是日期部分,因此值是这样的:'2014-07-20 00:00:00'
问题是a.TimeStamp
是一个包含日期和时间的DateTime字段。
所以上面的查询总是返回空
以任何方式我可以将a.TimeStamp
仅转换为Date,以便可以将a.TimeStamp
与a.TimeStamp
比较?
我得到的错误是:
The specified type member 'Date' is not supported in LINQ to Entities
欣赏它。
DateTime
字段具有Date
属性 ,因此我们可以简单地执行以下操作:
var details =
Uow
.EmployeeAttendances
.GetAllReadOnly()
.Where(a => a.EmployeeId == summary.EmployeeId
&& a.TimeStamp.Date == summary.Date)
.ToList();
正确的解决方案是:
在实体框架6中,您必须使用DbFunctions.TruncateTime。
var dates = Uow.EmployeeAttendances.GetAllReadOnly()
.Where(a => a.EmployeeId == summary.EmployeeId && System.Data.Entity.DbFunctions.TruncateTime(a.Timestamp) == attendanceDate)
.OrderBy(a=> a.Timestamp)
.ToList();
作为使用DbFunctions.TruncateTime的替代方法,您可以简单地执行以下操作:
var from = summary.Date;
var to = summary.Date.AddDays(1);
var details = Uow.EmployeeAttendances
.GetAllReadOnly()
.Where(a => a.EmployeeId == summary.EmployeeId && a.Timestamp >= from && a.Timestamp< to)
.ToList();
试试吧
string f = summary.ToString("MM/dd/yyyy");
summary= Convert.ToDateTime(f); // time at 12:00 start date
var details = Uow.EmployeeAttendances.GetAllReadOnly()
.Where(a=>a.EmployeeId== summary.EmployeeId &&
a.Timestamp == summary).ToList();
您可以使用DateTime.Compare例如
var details = Uow.EmployeeAttendances.GetAllReadOnly()
.Where(a => a.EmployeeId == summary.EmployeeId && DateTime.Compare(x.Timestamp .Date, summary.Date) == 0).ToList();
或使用EntityFunctions
var details = Uow.EmployeeAttendances.GetAllReadOnly()
.Where(a => a.EmployeeId == summary.EmployeeId && EntityFunctions.TruncateTime(x.Timestamp)== EntityFunctions.TruncateTime(summary.Date)).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.