LINQ to Entites中关于日期的逻辑运算注意事项(运用DbFunctions或EntityFunctions中的方法使之在执行时转换为相应的SQL日期函数表达式)

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

使用EF时,在Limda表达式中( query.Where(x => x.CheckInDate >= bd.Date);)编译没有异常,但运行时,执行查询的时候抛出了这个异常,

后来,在 http://sandeep-tada.blogspot.com/2014/02/the-specified-type-member-date-is-not.html  中发现,原来Linq中不允许使用DateTime成员Date     

Reason:  Entity Framework doesn't allow the use of the Date member of  DateTime  inside an LINQ query. And because of the use of  .Date member it throws the exception as when query get executed DateTime.Date cannot be converted to SQL statement.

 

为了避免出现这种情况,有两种解决办法:

一、将bd.Date在Linq外部赋值后再传入:

var bdDay = bd.Date;

 query.Where(x => x.CheckInDate >= bdDay );

二、通过DbFuntions功能方法来转义一下

(相关方法例如:System.Data.Entity.DbFunctions.TruncateTime、DbFunctions.DiffDays等)

 query.Where(x => x.CheckInDate >= DbFunctions.TruncateTime(bd.Date)); 

在Core中,与DbFunction对应的是EntityFunctions。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值