比较实体SQL中的日期

时间:2009-03-02 21:28:25

标签: entity-framework .net-3.5 entity-sql

比较日期的正确eSQL语法是什么?

等效的LINQ-to-Entities表达式如下所示:

var lastYearsShipments = from p in MyDataServiceContext.Products
                         where p.ShipDate.Value.Year == DateTime.Now.Year - 1
                         select p;

2 个答案:

答案 0 :(得分:2)

他们说这是acceptable to answer your own question,所以这里......

var predicate = string.Format(
    "Year(it.ShipDate) == Year(cast('{0}' as System.DateTime)) -1",
    System.DateTime.Now);

var lastYearsShipments = 
    myQuery.Products.Where(predicate); // myQuery is type ObjectQuery<T>

另请参阅:msdn documentation

答案 1 :(得分:0)

string datetimeFormatter = "yyyy-MM-dd HH:mm";

var predicate = string.Format("Year(it.ShipDate) == Year(DATETIME'{0}')) -1", System.DateTime.Now.ToString(datetimeFormatter)); 

var lastYearsShipments = myQuery.Products.Where(predicate);