Using DateTime.Add(TimeSpan) with LINQ

2020-02-14 07:05发布

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.

2条回答
霸刀☆藐视天下
2楼-- · 2020-02-14 08:01

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

查看更多
Fickle 薄情
3楼-- · 2020-02-14 08:02

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.

查看更多
登录 后发表回答