在LINQ to Entities中使用DateTime

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)

来源:http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/84d4e18b-7545-419b-9826-53ff1a0e2a62/


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)

  • 谢谢你回答,但我再次得到NotSupportedException.但是消息包含其他信息:类型为"System.Data.Objects.SqlClient"的指定方法'System.Nullable`1 [System.Int32] DatePart(System.String,System.Nullable`1 [System.DateTime])". SqlFunctions"无法转换为LINQ to Entities存储表达式.也许它是PostgreSQL的问题? (2认同)

Tim*_*m S 5

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)