Skip to content
欢迎扫码关注公众号

Entityframework DateTime.Now.Date 之 NotSupportedException

很简单的一个查询,结果报错。代码如下:

csharp
// Day 为 DateTime 类型
db.TableA.Where(m => m.Day == DateTime.Now.Date).ToList()

错误信息:

An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

Additional information: LINQ to Entities 不支持指定的类型成员“Date”。只支持初始值设定项、实体成员和实体导航属性。

但是代码改成下面这样就可以正常执行了:

csharp
DateTime today = DateTime.Now.Date;
db.TableA.Where(m => m.Day == today).ToList();

或者

csharp
db.TableA.Where(m => m.Day == DateTime.Now).ToList()

再或者

csharp
DateTime now = DateTime.Now;
db.TableA.Where(m => m.Day == now.Date).ToList();

根据错误消息可以看出 LINQ to Entities 里只支持初始值设定项、实体成员和实体导航属性。按照理解 DateTime.Now.Date 应该也属于初始值设定项才对。Why?

在 stackoverflow 上找到一篇相关的文章 Using DateTime in LINQ to Entities

还有个 MSDN 上的文章 Ignore time portion of datetime in a LINQ to Entity Framework query

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.