I have to run a query like the one bellow. It is actually more complex, but here is the part that matters:
var results =
from b in _context.Bookings
where b.ScheduleDate.Add(b.StartTime) >= DateTime.UtcNow
select b;
But it gives the following error:
LINQ to Entities does not recognize the method 'System.DateTime.Add method(System.TimeSpan)', and this method cannot be translated into a store expression.
How can I work around this?
Thanks in advance.
SqlFunctions
only works with Microsoft Sql Server.In pure EF you can write:
This works on all database adapters
Try using the
SqlFunctions.DateAdd
method in theSystem.Data.Objects.SqlClient
namespace. Documentation here. That will convert into the SQL methodDateAdd
, documented here. You might also be interested in usingDateDiff
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.