LINQ to Entities无法识别方法'System.TimeSpan Subtract(System.DateTime)
问题描述:
以下内容引发错误:
public FieldViewer GetFieldViewByFieldIDIPAndUserByDate( int fieldID, string ip, string userID, DateTime date )
{
return this.context.FieldViewers.Where( x =>
x.Field.FieldID == fieldID &&
x.Viewer.IPAddress == ip &&
x.Viewer.User.Id == userID &&
date.Subtract( x.Viewer.CreatedAt ).TotalMinutes >= 10 ).FirstOrDefault();
}
LINQ to Entities无法识别方法'System.TimeSpan Subtract(System.DateTime)',并且该方法无法转换为商店表达式.
LINQ to Entities does not recognize the method 'System.TimeSpan Subtract(System.DateTime)' method, and this method cannot be translated into a store expression.
如何解决此问题,因为我需要为每个查询减去.
How do I go about solving this as I need to subtract per query instead.
答
EntityFunctions.DiffMinutes
对于您的情况将无效.您应该这样做
EntityFunctions.DiffMinutes
for your case will be inefficient. You should do this way
public FieldViewer GetFieldViewByFieldIDIPAndUserByDate( int fieldID, string ip, string userID, DateTime date )
{
var tenMinThreshold = date - TimeSpan.FromMinutes(10);
return this.context.FieldViewers.Where( x =>
x.Field.FieldID == fieldID &&
x.Viewer.IPAddress == ip &&
x.Viewer.User.Id == userID &&
x.Viewer.CreatedAt <= tenMinThreshold).FirstOrDefault();
}