掌握 LINQ to SQL 中 Null 處理與 .NET 字串/日期方法對應 SQL 函數的對照表,避免查詢轉譯錯誤。
var q = from e in db.Employees
where e.ReportsToEmployee == null
select e;
var q = from e in db.Employees
where !e.ReportsTo.HasValue
select e;
var q = from e in db.Employees
where e.ReportsTo.HasValue
select new { e.FirstName, e.LastName, ReportsTo = e.ReportsTo.Value };
.Value 可省略,編譯器自動處理。
| .NET 方法 | SQL Server 函數 |
|---|---|
| Contains | LIKE '%...%' |
| StartsWith | LIKE '...%' |
| EndsWith | LIKE '%...' |
| Substring | SUBSTRING |
| ToLower/ToUpper | LOWER/UPPER |
| Trim | LTRIM(RTRIM(...)) |
| Length | LEN |
| .NET 屬性/方法 | SQL Server 函數 |
|---|---|
| Year, Month, Day | DATEPART(year/month/day, ...) |
| Hour, Minute, Second | DATEPART(hour/minute/second, ...) |
| Date | CONVERT(DATE, ...) |
| DayOfWeek | DATEPART(weekday, ...) |
不支援的方法(如 Regex.Match)需搭配 AsEnumerable() 移至客戶端執行。