I have the following Linq to Entity:
var details = Uow.EmployeeAttendances.GetAllReadOnly()
.Where(a => a.EmployeeId == summary.EmployeeId && a.Timestamp == summary.Date)
.ToList();
summary.Date
is just the date part so the value is like this: '2014-07-20 00:00:00'
The problem is that a.TimeStamp
is a DateTime field with both date and time.
So the above query always return empty
Any way I can convert a.TimeStamp
just to Date so I can compare apples with apples?
The error that I get is:
The specified type member 'Date' is not supported in LINQ to Entities
Appreciate it.
DateTime
fields have a Date
property , so we can simply do:
var details =
Uow
.EmployeeAttendances
.GetAllReadOnly()
.Where(a => a.EmployeeId == summary.EmployeeId
&& a.TimeStamp.Date == summary.Date)
.ToList();
The right solution is:
In Entity Framework 6, you have to use 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();
As an alternative to using DbFunctions.TruncateTime, you can simply do the following:
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();
Try it
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();
you can use DateTime.Compare for example
var details = Uow.EmployeeAttendances.GetAllReadOnly()
.Where(a => a.EmployeeId == summary.EmployeeId && DateTime.Compare(x.Timestamp .Date, summary.Date) == 0).ToList();
or use EntityFunctions
var details = Uow.EmployeeAttendances.GetAllReadOnly()
.Where(a => a.EmployeeId == summary.EmployeeId && EntityFunctions.TruncateTime(x.Timestamp)== EntityFunctions.TruncateTime(summary.Date)).ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.