C# LINQ to实体无法识别方法';System.TimeSpan减法(System.DateTime)
以下内容引发了一个错误:C# LINQ to实体无法识别方法';System.TimeSpan减法(System.DateTime),c#,linq,entity-framework,C#,Linq,Entity Framework,以下内容引发了一个错误: public FieldViewer GetFieldViewByFieldIDIPAndUserByDate( int fieldID, string ip, string userID, DateTime date ) { return this.context.FieldViewers.Where( x => x.Field.FieldID == fieldID && x.Viewer.IPAddres
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 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();
}
另一种方法是使用其中一种方法,如。尝试以下方法以分钟为单位找出差异:
EntityFunctions.DiffMinutes(date,x.Viewer.CreatedAt)>=10
资料来源:
由于此api现已过时(感谢您在@Jimmyt1988中指出这一点),因此请改用:
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();
}
public FieldViewer GetFieldViewByFieldIDIPAndUserByDate(int-fieldID,string-ip,string-userID,DateTime-date)
{
var tenMinThreshold=日期-时间跨度,从分钟(10);
返回this.context.FieldViewers.Where(x=>
x、 Field.FieldID==FieldID&&
x、 Viewer.IPAddress==ip&&
x、 Viewer.User.Id==userID&&
x、 Viewer.CreatedAt mably?示例用法EntityFunctions的可能重复项已过时,您可以使用DbFunctions
。为此,它工作得非常好,并且在db调用之前就完成了!