2011-09-16 21 views
3

我得到一個例外,當我執行此代碼:LINQ:轉換GUID來串

var result = from menu in menuBus.GetMenus() 
      orderby menu.InternalName 
      select new 
      { 
       Value = menu.ID.ToString(), 
       Text = menu.InternalName 
      }; 

var result = allMenus.ToList(); 

錯誤消息說:LINQ到實體無法識別方法「System.String的ToString()」方法,並且此方法不能被轉換爲存儲的表達式。

所以,我猜是Value = menu.ID.ToString()出了問題。 ID屬性被定義爲GUID(MS SQL中的UniqueIdentifier)。

有沒有人有解決方案?

非常感謝!

回答

6

您需要查詢數據庫後運行通過另一個查詢列表。

var result = (from menu in menuBus.GetMenus() 
         orderby menu.InternalName 
         select new 
         { 
          Value = menu.ID, 
          Text = menu.InternalName 
         }).ToList(); 


var result2 = (from menu in result select new {Value=menu.Value.ToString(),Text=menu.Text}).ToList(); 
+0

謝謝George,您的解決方案對我來說非常棒! – Ingmar

1

據我所知,你的linq查詢中不能有.ToString(),因爲linq to entity不知道該怎麼處理它(因爲它不能將它轉換成sql語句)......你可以有選擇部分作爲

select new 
{ 
    Value = menu.ID, 
    Test = menu.InternalName 
} 

,然後就用戶foreach循環和值複製到另一個列表在轉換GUID來串

+1

這裏不需要foreach,你可以使用額外的linq來查詢對象。 –