LINQ to Entities does not recognize the method 'Int64 Max(Int64, Int64)' method, and this method cannot be translated into a store expression

故事扮演 提交于 2019-12-24 02:47:49

问题


I'm getting this error message during runtime

LINQ to Entities does not recognize the method 'Int64 Max(Int64, Int64)' method, and this method cannot be translated into a store expression.

when I try to do this:

return _dbContext.Appointment.Where(x => Math.Max(x.Appointment.StartTime.Ticks, startTime.Ticks) <= Math.Min(x.Appointment.EndTime.Ticks, endTime.Ticks));

The idea behind this query is that "if the latest start time is before the earliest end time, then you have some overlap/touching" in date and time.

Is there any way to get this line working? I already checked if EntityFunctions has 'something', which wasn't the case.


回答1:


You must always keep in mind that every IQueryable provider is implemented in its own way. That query would work in Linq to Objects (as it does not gets translated to anything) but may or may not work in IQueryable providers.

In your specific case, it's telling you that it has no idea on how to translate Math.Max and Math.Min into SQL commands. And that's perfectly correct, since EF doesn't recognize those methods.

In my opinion the easiest way to accomplish what you need is reading the max and the min value with two different queries and then do your logic in plain c#. Something like this:

var min = mycontext.MyDbSet.Min(c => c.Field);
var max = mycontext.MyDbSet.Max(c => c.Field);
if (max <= min)
{
    // do something
}



回答2:


Max and Min can be implemented like this:

public static long Max(long a, long b)
{
    return a < b ? b : a;
}
public static long Min(long a, long b)
{
    return a < b ? a : b;
}

Since LINQ to Entities understands ? :, you will be able to inline these into your expression. Also, since Ticks is not supported, but DateTime comparison is...

Math.Max(x.Appointment.StartTime.Ticks, startTime.Ticks)

Becomes

(x.Appointment.StartTime < startTime ? startTime : x.Appointment.StartTime)


来源:https://stackoverflow.com/questions/18124923/linq-to-entities-does-not-recognize-the-method-int64-maxint64-int64-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!