LINQ 中 DateTime.Add(TimeSpan) 的使用问题

.Net技术 码拜 5年前 (2015-12-18) 977次浏览 0个评论

LINQ 中使用DateTime.Add(TimeSpan)方法执行一个查询,执行后发生如下错误:LINQ to Entities does not recognize the method ‘System.DateTime.Add method(System.TimeSpan)’, and this method cannot be translated into a store expression.


var results =
    from b in _context.Bookings
    where b.ScheduleDate.Add(b.StartTime) >= DateTime.UtcNow
    select b;



Try using the SqlFunctions.DateAdd method in the System.Data.Objects.SqlClient namespace. Documentation here. That will convert into the SQL method DateAdd, documented here. You might also be interested in using DateDiff instead, documented here.

In general, look at SqlFunctions for “common language runtime (CLR) methods that call functions in the database in LINQ to Entities queries.” LINQ to Entities cannot convert any method call into SQL, but the functions in that class will work.

Your other option is to execute the LINQ to Entities query (using ToList or something similar) and then perform the logic in memory.


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明LINQ 中 DateTime.Add(TimeSpan) 的使用问题
喜欢 (0)
分享 (0)