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)’方法,并且此方法无法转换为商店表达式。

我如何解决这个问题,因为我需要减去每个查询。

您的案例的EntityFunctions.DiffMinutes效率低下。 你应该这样做

 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(); } 

解决此问题的一种方法是使用LINQ to Objects提供程序在LINQ to Entities提供程序之外执行该部分过滤。 为此,请在该操作之前追加对AsEnumerable()的调用:

 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) .AsEnumerable() .Where(x => date.Subtract( x.Viewer.CreatedAt ).TotalMinutes >= 10) .FirstOrDefault(); } 

另一种方法是使用专门的LINQ to Entities操作之一 ,如DiffMinutes

试试这个以分钟为单位找出差异:

EntityFunctions.DiffMinutes(date, x.Viewer.CreatedAt) >= 10

资料来源:

如何从自定义时间减去EntityFunctions.TruncateTime

EntityFunctions.DiffMinutes

因为这个api现在已经过时了(感谢你指出这个@ Jimmyt1988),而是使用: DbFunctions.DiffMinutes