2012-10-01 33 views
4

使用DateTime.AddDays(X)我有這樣的代碼:如何在實體框架

from pr in e.ProgramSetup.Include("Program").Include("Program.Client") 
     where pr.DateBegin < DateTime.Now 
     && pr.DateEnd > DateTime.Now.AddDays(pr.DateEndOffset) 
select pr).ToList(); 

它不工作,因爲AddDays()無法使用生成SQL。

那麼還有其他方法嗎?現在,我選擇所有內容並通過foreach進行最終過濾,但在我看來這不是一種好方法。

問題是,pr.DateEndOffset也只是在分貝,它不是恆定的...

回答

7

您需要使用映射到規範函數的EntityFunctions之一。下面是AddDays一個例子:

public class MyEntity 
{ 
    public int Id { get; set; } 
    public DateTime Date { get; set; } 
} 

public class MyContext : DbContext 
{ 
    public DbSet<MyEntity> Entities { get; set; } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     using (var ctx = new MyContext()) 
     { 
      if (!ctx.Entities.Any()) 
      { 
       ctx.Entities.Add(new MyEntity() { Date = new DateTime(2000, 1, 1) }); 
       ctx.Entities.Add(new MyEntity() { Date = new DateTime(2012, 10, 1) }); 
       ctx.Entities.Add(new MyEntity() { Date = new DateTime(2012, 12, 12) }); 
       ctx.SaveChanges(); 
      } 

      var q = from e in ctx.Entities 
        where e.Date > EntityFunctions.AddDays(new DateTime(2012, 10, 1), 10) 
        select e; 

      foreach (var entity in q) 
      { 
       Console.WriteLine("{0} {1}", entity.Id, entity.Date); 
      } 
     } 
    } 
} 
+0

你試試這個?如果是這樣,你安裝了什麼連接器?我試過了,它不起作用。它說它不能翻譯AddDays。我不得不在DB中創建AddDays函數 - 然後它工作 – sirrocco

+0

對於Sql Server,這應該是開箱即用的。你使用的是哪個數據庫? – Pawel

+0

MySQL ..東西總是在Sql Server中工作:) – sirrocco

0
using System.Data.Entity; 
... 
DbFunctions.AddDays(dateFromDataStore, numDaysToAdd); 
+0

如果你解釋你的解決方案會很好。 –