[程式]Linq 未實作的功能
MyContext context = new MyContext();
int count = context.Logs.Count(m => m.CreateDate.Value.ToShortDateString() == DateTime.Today.ToShortDateString());
上面的式子在使用了 linq to Sql, 其中 Logs 資料表中有一個欄位 CreateDate 是 Sql 的 DateTime 型別,在 lamba Expression 中,把它當做 DateTime 型別使用,於是使用了 ToShortDateString 這個方法,編譯一切正常,但執行時,卻發生了例外。
不死心的,將上述的式子改為:
MyContext context = new MyContext();
int count = context.Logs.Count(m => m.CreateDate.Value.ToString("yyyyMMdd") == DateTime.Today.ToString("yyyyMMdd"));
依然出錯,最後只好將式子改為
MyContext context = new MyContext();
int count = context.Logs.Count(m => m.CreateDate.Value.Date == DateTime.Today.Date);
才終於過關,但這一切過程都是 runTime 時才發生問題,原本強調 var 型別的動態性,與強型別編譯的好處,以減少錯誤的發生,但眼前卻顯得一切都不可靠。
最後終於在 msdn 中找到了答案:
http://msdn.microsoft.com/en-us/library/bb425822.aspx
節錄最後面一段:
System.DateTime
Implemented
- Constructors:
DateTime(year, month, day)
DateTime(year, month, day, hour, minutes, seconds)
DateTime(year, month, day, hour, minutes, seconds, milliseconds)- Operators:
Comparisons
DateTime – DateTime (gives TimeSpan)
DateTime + TimeSpan (gives DateTime)
DateTime – TimeSpan (gives DateTime)- Static (Shared) methods:
Add(TimeSpan), AddTicks(Long),
AddDays/Hours/Milliseconds/Minutes (Double)
AddMonths/Years(Int32)
Equals- Non-static (Instance) methods / properties:
Day, Month, Year, Hour, Minute, Second, Millisecond, DayOfWeek
CompareTo(DateTime)
TimeOfDay()
Equals
ToString()Difference from .NET
SQL's datetime values are rounded to .000, .003 or .007 seconds, so it is less precise than those of .NET.
The range of SQL's datetime starts at January 1st, 1753.
SQL does not have a built-in type for TimeSpan. It uses different DATEDIFF methods that return 32-bit integers. One is DATEDIFF(DAY,...), which gives the number of days; another is DATEDIFF(MILLISECOND,...), which gives the number of milliseconds. An error results if the DateTimes are more than 24 days apart. In contrast, .NET uses 64-bit integers and measures TimeSpans in ticks.
To get as close as possible to the .NET semantics in SQL, LINQ to SQL translates TimeSpans into 64-bit integers and uses the two DATEDIFF methods mentioned above to calculate the number of ticks between two dates.
DateTime
UtcNow is evaluated on the client when the query is translated (like any expression that does not involve database data).
Not implemented
IsDaylightSavingTime()
IsLeapYear(Int32)
DaysInMonth(Int32, Int32)
ToBinary()
ToFileTime()
ToFileTimeUtc()
ToLongDateString()
ToLongTimeString()
ToOADate()
ToShortDateString()
ToShortTimeString()
ToUniversalTime()
FromBinary(Long), FileTime, FileTimeUtc, OADate
GetDateTimeFormats(...)
constructor DateTime(Long)
Parse(String)
DayOfYear
如上所述,在System.DateTime 中, ToShortDateTime 都是未實現(作)的
可是這樣的東西竟然可以編譯過關,實在讓人覺得 linq 太隨便了
只能說 linq 帶來了方便,但也帶來了更多 runTime 時的危險
留言