2008-10-18 77 views

回答

29

我假設你在where子句中討論。它基本上與您在其他地方比較兩個DateTime對象的方式基本相同。

using (DataContext context = new DataContext()) { 
    var query = from t in context.table 
       where t.CreateDate.Date < DateTime.Today.AddMonths(-1) 
       select t; 
} 
5

只需添加,在LINQ To Entities中,您必須與變量進行比較。例如:

 DateTime lastMonth = DateTime.Today.AddMonths(-1); 
     using (var db = new MyEntities()) 
     { 
      var query = from s in db.ViewOrTable 
         orderby s.ColName 
         where (s.StartDate > lastMonth) 
         select s; 

      _dsResults = query.ToList(); 
     } 
0

如果你不希望你的代碼拋出

LINQ to Entities does not recognize the method 'System.DateTime AddYears(Int32)' method, and this method cannot be translated into a store expression. 

我會用DbFunctions.AddYears建議。另外,如果你只關心日期,而不是時間,你可以使用DbFunctions.TruncateTime

事情是這個 -

DbFunctions.TruncateTime(x.date) == 
DbFunctions.TruncateTime(DbFunctions.AddYears(DateTime.Today, 1))