LINQ to Entities无法识别方法'System.TimeSpan Subtract(System.DateTime)'方法

Rag*_*h S 34 c# linq linq-to-entities entity-framework linq-to-sql

我尝试在当前日期的60天30天20天内选择数据库中的记录.

请在下面查看此查询.

 var uploads = (
                from files in _fileuploadRepository.Table
                join product in _productRepository.Table on files.Event equals product.Id
                where
                    (
                product.EventDate != null &&
                    (product.EventDate.Subtract(DateTime.Now).Days <= 60 && product.EventDate.Subtract(DateTime.Now).Days >= 60) ||
                    (product.EventDate.Subtract(DateTime.Now).Days <= 30 && product.EventDate.Subtract(DateTime.Now).Days >= 30) ||
                    (product.EventDate.Subtract(DateTime.Now).Days <= 20 && product.EventDate.Subtract(DateTime.Now).Days >= 20))
                    &&
                files.IsSkiped == false
                select files;
            ).ToList();
Run Code Online (Sandbox Code Playgroud)

但是此查询发生错误.

在此输入图像描述

我很无能为力.请帮忙.

sca*_*tag 54

你可以使用这个EntityFunctions.DiffDays方法

EntityFunctions.DiffDays(product.EventDate, DateTime.Now) //this will return the difference in days
Run Code Online (Sandbox Code Playgroud)

UPDATE

EntityFunctions现在已经过时,因此您应该使用DBFunctions.

System.Data.Entity.DbFunctions.DiffDays(product.EventDate, DateTime.Now)
Run Code Online (Sandbox Code Playgroud)

  • EntityFunctions现在已过时:改为使用System.Data.Entity.DbFunctions. (19认同)

Jon*_*eet 36

最简单的方法是执行查询之前计算出边界:

// Only evaluate DateTime.Now once for consistency. You might want DateTime.Today instead.
DateTime now = DateTime.Now;
DateTime nowPlus60Days = now.AddDays(60);
DateTime nowPlus30Days = now.AddDays(30);
DateTime nowPlus20Days = now.AddDays(20);

var query = ...
            where product.EventDate <= nowPlus60Days
            ...
Run Code Online (Sandbox Code Playgroud)

请注意,您当前的查询甚至没有意义,因为每个"或"'d子句都声明给定的计算小于或等于某个值大于或等于相同的值.如果你想要简单的"等于",那就用它吧.如果没有,目前还不清楚是什么你正在尝试做的.

如果你想把这些值分成"小于20","20-30","30-60","超过60",你需要使用某种形式的分组.


Dmi*_*nov 5

这应该有效:

using System.Data.Entity.SqlServer;

where (int)SqlFunctions.DateDiff("day", product.EventDate, DateTime.Now) <= 60
Run Code Online (Sandbox Code Playgroud)