LINQ to Entities does not recognize the method 'System.TimeSpan Subtract(System.DateTime)

后端 未结 3 1790
北荒
北荒 2021-01-21 03:41

The following throws an error:

public FieldViewer GetFieldViewByFieldIDIPAndUserByDate( int fieldID, string ip, string userID, DateTime date )
{
    return this.         


        
相关标签:
3条回答
  • 2021-01-21 03:47

    Try this to find the difference in minutes:

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

    Sources:

    How to subtract EntityFunctions.TruncateTime from custom time

    EntityFunctions.DiffMinutes

    As this api is now obsolete (thanks for pointing this out @Jimmyt1988), instead use: DbFunctions.DiffMinutes

    0 讨论(0)
  • 2021-01-21 04:03

    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();
    }
    
    0 讨论(0)
  • 2021-01-21 04:10

    One way to fix this is to perform that part of the filtering outside of the LINQ to Entities provider, using the LINQ to Objects provider. To do that, append a call to AsEnumerable() before that operation:

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

    Another way is to use one of the specialized LINQ to Entities operations, like DiffMinutes.

    0 讨论(0)
提交回复
热议问题