C# LINQ to实体无法识别“System.TimeSpan Subtract(System.DateTime)”方法

C# LINQ to实体无法识别“System.TimeSpan Subtract(System.DateTime)”方法,c#,linq,entity-framework,linq-to-sql,linq-to-entities,C#,Linq,Entity Framework,Linq To Sql,Linq To Entities,我尝试在数据库中选择60天30天20天当前日期的不同记录 请参阅下面的查询 var uploads = ( from files in _fileuploadRepository.Table join product in _productRepository.Table on files.Event equals product.Id where (

我尝试在数据库中选择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();
但是在这个查询中发生了一个错误


我不懂。请提供帮助。

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

// 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
            ...
请注意,您当前的查询甚至没有真正意义,因为每个or'd子句都表示给定的计算既小于或等于一个值,又大于或等于同一个值。如果你想让simple等于,那就用这个。如果不是,你不清楚你想做什么

如果您试图将值分为小于20、20-30、30-60、大于60,则需要使用某种形式的分组。

您可以使用EntityFunctions.DiffDays方法

更新

EntityFunctions现在已过时,因此应改用DBFunctions

System.Data.Entity.DbFunctions.DiffDays(product.EventDate, DateTime.Now)

为了补充斯卡塔格的答案

没有直接提到DiffDays返回的值是否为负值以及何时为负值,所以我想在这里提供这些信息:

如果参数1的日期大于参数2的日期,则结果将为负值

例如,给定一个具有非空字段ScheduledDeliveryDate的表Deliveries,该字段可以具有相对于当前日期的过去和将来的值,此查询将获取在当前日期/时间的2天内具有过去和将来的交货日期/时间的所有记录:

DateTime now = DateTime.Now;
var results = from d in Deliveries
    where (DbFunctions.DiffDays(d.ScheduledDeliveryDate, now) < 2
        && DbFunctions.DiffDays(d.ScheduledDeliveryDate, now) > -2)
    select d;
这应该起作用:

using System.Data.Entity.SqlServer;

where (int)SqlFunctions.DateDiff("day", product.EventDate, DateTime.Now) <= 60

您是否在lambda声明之外进行计算。当它在lambda中时,就像您正在使用它一样,您正在尝试让EntityFramework在它不打算这样做的情况下进行计算。因此LINQ to SQL不会转换像product.EventDate.SubtractDateTime.Now这样的表达式。在C语言中,另一种表示法是product.EventDate-DateTime。有人知道这是否适用于LINQtoSQL吗?毕竟,在SQL方言中也可以减法日期。@JeppeStigNielsen For EF您可以使用EntityFunctions.DiffDaysEntityFunctions现在已经过时:改用System.Data.Entity.DbFunctions。
using System.Data.Entity.SqlServer;

where (int)SqlFunctions.DateDiff("day", product.EventDate, DateTime.Now) <= 60