本文介绍了在LINQ to Entities中使用DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个PostgreSQL数据库通过实体框架代码首先与程序进行交互。数据库包含一个具有访问类型的DateTime表的users表。
应用程序描述为;
public class Users
{...
[必需]
[列(访问)]
public DateTime VisitDate
...
}
我试图运行此查询;
var rslt = context.Visitors.Where(v => v.VisitDate.Date == DateTime.Now.Date).ToList()
但是得到一个例外: NotSupportedException
有什么问题?
解决方案
DateTime.Date
不支持属性。您必须使用方法。最终将在生成的SQL查询中使用 DATEPART
TSQL
方法。
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();
I have a PostgreSQL database that interacts with the program through Entity Framework Code First.
Database contains a table "users" that has column "visit" type of DateTime.
The application is described as;
public class Users
{ ...
[Required]
[Column("visit")]
public DateTime VisitDate
...
}
I trying to run this query;
var rslt = context.Visitors.Where(v => v.VisitDate.Date == DateTime.Now.Date).ToList()
But getting an exception: NotSupportedException
What's wrong?
解决方案
DateTime.Date
property is not supported. You have to use SqlFunctions.DatePart
method instead. It will end up with DATEPART
TSQL
method within generated SQL query.
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();
这篇关于在LINQ to Entities中使用DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!