Phillippe Santana
Phillippe Santana

Reputation: 3116

Using DateTime.Add(TimeSpan) with LINQ

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.

Upvotes: 3

Views: 6056

Answers (2)

Rafael
Rafael

Reputation: 2753

SqlFunctions only works with Microsoft Sql Server.

In pure EF you can write:

DbFunctions.AddMilliseconds(x.Date, DbFunctions.DiffMilliseconds(TimeSpan.Zero, x.Time))

This works on all database adapters

Upvotes: 8

Ben Reich
Ben Reich

Reputation: 16324

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.

Upvotes: 7

Related Questions