Linq compare by date problem
My Code is here
VisitorLog log = db.Context.VisitorLogs
.Where(vl=>vl.inDate.Date == DateTime.Now.Date).FirstOrDefault();
this error shown
The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported
How to compare by only date (skip time)
in LINQ?
CORRECT ANSWER
var currentDate = DateTime.Now;
Visit开发者_如何学JAVAorLog log = db.Context.VisitorLogs
.Where(vl => EntityFunctions.DiffDays(vl.inDate, currentDate) == 0).FirstOrDefault();
Thanks for answered.
You should use entity canonical functions see this, and for all canonical functions see this. You can use Day, year and Month to solve your problem.
Do this instead,
var currentDate = DateTime.Now.Date;
VisitorLog log = db.Context.VisitorLogs
.Where(vl=>vl.inDate.Date == currentDate).FirstOrDefault();
But this could be tricky if vl.inDate.Date includes the time, but it will not error out, just that there may not be a match
EDIT:
Given that the didn't work, can you try this work around
var currentDate = DateTime.Now.Date;
var timeIn24HrsTime = DateTime.Now.AddDays(1).Date;
VisitorLog log = db.Context.VisitorLogs
.Where(vl=>vl.inDate >= currentDate && vl.inDate < timeIn24HrsTime).FirstOrDefault();
You can try this also:
context.Products.Where(x=> (
EntityFunctions.TruncateTime(x.CreatedDate) >=
EntityFunctions.TruncateTime(startdate))
&& (EntityFunctions.TruncateTime(x.CreatedDate) <=
EntityFunctions.TruncateTime(enddate)))
According to your requirement you should try for:
var currentDate = DateTime.Now;
VisitorLog log = db.Context.VisitorLogs.Where(vl =>
EntityFunctions.DiffDays(EntityFunctions.TruncateTime(vl.inDate),
EntityFunctions.TruncateTime(currentDate)) == 0).FirstOrDefault();
Try
vl.inDate.Date.Equals(DateTime.Now.Date)
精彩评论