max*_*max 9 c# datetime linq-to-entities
我有一个PostgreSQL数据库,通过Entity Framework Code First与程序交互.
数据库包含一个表"users",其具有"访问"类型的DateTime.
该应用程序被描述为;
public class Users
{ ...
[Required]
[Column("visit")]
public DateTime VisitDate
...
}
Run Code Online (Sandbox Code Playgroud)
我试图运行此查询;
var rslt = context.Visitors.Where(v => v.VisitDate.Date == DateTime.Now.Date).ToList()
Run Code Online (Sandbox Code Playgroud)
但得到一个例外: NotSupportedException
怎么了?
May*_*rad 13
使用EntityFunction类修剪时间部分.
using System.Data.Objects;
var bla = (from log in context.Contacts
where EntityFunctions.TruncateTime(log.ModifiedDate) == EntityFunctions.TruncateTime(today.Date)
select log).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
Mar*_*zek 11
DateTime.Date
属性不受支持.你必须使用SqlFunctions.DatePart
方法.它将以DATEPART
TSQL
生成的SQL查询中的方法结束.
var rslt = context.Visitors
.Where(v => SqlFunctions.DatePart("year", v.VisitDate) == SqlFunctions.DatePart("year", DateTime.Now))
.Where(v => SqlFunctions.DatePart("dayofyear", v.VisitDate) == SqlFunctions.DatePart("dayofyear", DateTime.Now))
.ToList();
Run Code Online (Sandbox Code Playgroud)
Mayur Borad的答案(IMHO比公认的答案更正确)已经过时:
System.Data.Entity.Core.Objects.EntityFunctions
已过时。您应该System.Data.Entity.DbFunctions
改用。
var today = DateTime.Today; // (Time already removed)
var bla = context.Contacts
.FirstOrDefault(x => DbFunctions.TruncateTime(x.ModifiedDate) == today);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
22989 次 |
最近记录: |