2013-03-07 100 views
30

我嘗試在60天內選擇數據庫中的記錄30天20天當前日期不同。LINQ to Entities不能識別方法'System.TimeSpan Subtract(System.DateTime)'方法

請在下面看到此查詢。

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

但是這個查詢發生了錯誤。

enter image description here

我無言以對。請幫忙。

+1

你的拉姆達聲明之外的計算。當它在你使用它的lambda內時,你試圖讓EntityFramework在不打算這樣做時進行計算。 – Middas 2013-03-07 06:14:01

+0

所以LINQ to SQL不會「翻譯」像'product.EventDate.Subtract(DateTime.Now)'這樣的表達式。在C#中,替代符號是'product.EventDate - DateTime.Now',其中一個使用[負號('-')運算符](http://msdn.microsoft.com/zh-cn/library/1905yhe2)。 ASPX)。有誰知道_that_是否適用於LINQ to SQL?畢竟,在SQL方言中,日期的減法也是可能的。 – 2013-03-07 06:47:11

+0

@JeppeStigNielsen對於EF,您可以使用EntityFunctions.DiffDays – scartag 2013-03-07 07:09:13

回答

33

最簡單的方法是制定出之前執行查詢的範圍:

// 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 
      ... 

注意,目前的查詢甚至沒有什麼意義,因爲每個「或」'd子句說明給定的計算值小於或等於大於或等於相同值的值。如果你想簡單的「等於」,那麼使用它。如果不是,你不清楚試圖做什麼。

如果你想把值分成「小於20」,「20-30」,「30-60」,「大於60」,你需要使用某種形式的分組。

44

你可以使用EntityFunctions.DiffDays方法

EntityFunctions.DiffDays(product.EventDate, DateTime.Now) //this will return the difference in days 

UPDATE

EntityFunctions現在已經過時了,所以你應該使用DBFunctions代替。

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

EntityFunctions現在已過時:改爲使用System.Data.Entity.DbFunctions。 – celerno 2014-03-07 23:27:30

2

要添加到scartag的回答,

MSDN documentation for DbFunctions.DiffDays沒有直接提到由DiffDays()返回的值是否以及何時會是負的,所以我想我會在這裏提供的信息:

當參數1日期大於(即將來相對於)參數2日期時,結果將爲負數。

例如,給定一個表Deliveries與非空場ScheduledDeliveryDate可以兼得過去和未來相對於當前日期值,該查詢將獲得的所有記錄與內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; 
3

這應該工作:

using System.Data.Entity.SqlServer; 

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