2009-11-20 86 views
5

我想直接從LINQ-to-Entities查詢表達式獲取格式化的日期字符串。Linq-to-Entities:格式選擇查詢表達式中的日期

nonBusinessDays = (from ac in db.AdminCalendar 
        where ac.DateTimeValue >= calendarStartDate && ac.DateTimeValue <= calendarEndDate && ac.IsBusinessDay == false 
        select ac.MonthValue + "/" + ac.DayOfMonth + "/" + ac.FullYear).ToList(); 

但是,我得到的folloinw錯誤消息: 「無法轉換類型'System.Nullable`1爲鍵入‘System.Object的’LINQ到實體僅支持鑄造實體數據模型的基本類型。 「

除了遍歷結果集,還有什麼辦法可以做到嗎? 謝謝! 安倍

回答

9

我找到了一個解決辦法:

nonBusinessDays = (from dt in 
          (from ac in db.AdminCalendar 
          where ac.DateTimeValue >= calendarStartDate && ac.DateTimeValue <= calendarEndDate && ac.IsBusinessDay == false 
          select ac.DateTimeValue).ToList() 
        select string.Format("{0:M/d/yyyy}", dt)).ToList(); 
+1

您遇到的問題是,它的企圖的ToString轉化爲有效的SQL執行在服務器上 - 然後它沒有做到。嵌套查詢意味着你正在分離無法從查詢中完成的.ToString,因此它可以工作 – Murph 2009-11-21 13:24:28

+1

謝謝! 現在有道理; LINQ試圖將函數映射到一個不存在的SQL函數。 我的解決方法是首先將數據獲取到列表中並從那裏處理列表。 – Abe 2009-12-02 16:54:54

+0

懶惰加載是罪魁禍首。 – 2013-01-23 22:26:53

0

試着改變你的選擇要使用的ToString:

nonBusinessDays = (from ac in db.AdminCalendar 
        where ac.DateTimeValue >= calendarStartDate && ac.DateTimeValue <= calendarEndDate && ac.IsBusinessDay == false 
        select ac.DateTimeValue.ToString("MM/dd/yyyy")).ToList(); 
+0

不幸的是,你不能運行ToString方法;這裏是我得到的異常: LINQ to Entities無法識別方法'System.String ToString(System.String)'方法,並且此方法無法轉換爲存儲表達式。 – Abe 2009-11-20 23:36:07