2010-03-25 30 views
13

嗨,這似乎像它應該工作,LINQ的Guid的toString()

from something in collectionofsomestuff  
select new SelectListItem(){Text = something.Name, Value = something.SomeGuid.ToString(), Selected = false}; 

當我試圖做到這一點不工作給我錯誤

LINQ到實體不承認方法'System.String ToString()'方法,並且此方法不能被轉換爲存儲表達式。

是否有解決方法?

+0

從哪個範圍做「Name」和「SomeGuid」來?目前尚不清楚。 – spender 2010-03-25 01:15:38

+0

對不起。是更好嗎? – Sevki 2010-03-25 01:20:34

回答

5

並非所有的CLR方法都可以與Linq-to-Entities一起使用。 ToString()似乎是其中之一。

看看CLR Method to Canonical Function Mapping

也許嘗試將GUID設置爲Linq之外的字符串變量。

string myGuid = SomeGuid.ToString(); 

from something in collectionofsomestuff  
select new SelectListItem(){Text = Name, Value = myGuid, Selected = false}; 
4

我不會說的LINQ查詢表達式太清楚,但下面應該做的伎倆:

collectionofsomestuff //here it's LinqToEntities 
    .Select(something=>new{something.Name,something.SomeGuid}) 
    .ToArray() //From here on it's LinqToObjects 
    .Select(s=>new SelectListItem() 
     { 
      Text = s.Name, 
      Value = s.SomeGuid.ToString(), 
      Selected = false 
     }) 
+0

對不起,同樣的錯誤... – Sevki 2010-03-25 02:01:36

+0

正是我在找什麼。十分感謝! – defines 2011-06-17 19:03:18

1

最後我做一個foreach像這樣

  List<SelectListItem> list = new List<SelectListItem>(); 
     foreach (SomeThing something in collectionofsomestuff) 
     { 
      list.Add(new SelectListItem(){Text = something.Name,Selected = false,Value = something.SomeGuid.ToString()}); 
     } 

這是唯一的辦法,我可以得到它的工作..這不是我想要做的艱難..

1

創建一個構造函數爲SelectLi接受你的價值作爲一個Guid和ToString它在那裏的系統。現在打電話給你的查詢,像這樣:

from something in collectionofsomestuff select new SelectListItem(something.Name, something.SomeGuid, false); 
5

你可以在數據庫中的記錄,然後將它們變成列表或陣列中使用ToList()或ToArray的(),然後使用對象。 例如(這是LINQ到實體):

var list = collectionofsomestuff.select(c => c).ToList(); 
from something in list 
select new SelectListItem(){Text = something.Name, Value = something.SomeGuid.ToString(), Selected = false}; 
+0

我認爲這是最好的答案。在調用'.Select(new SelectListItem(...')之前,您還可以使用'.AsQueryable' – user1477388 2014-03-30 15:03:06

1

我有同樣的問題,我結束了我的改變對象的定義來解決這個問題。這是一個完整的黑客攻擊,但它可以讓我從查詢直接填充數據:

[DataContract] 
public class DeviceInfo 
{ 
    public Guid DeviceGuid 
    { 
     set 
     { 
      DeviceID = value.ToString(); 
     } 
    } 
    [DataMember] 
    public string DeviceID { get; set; } 
} 

和查詢工作方式設計的,因爲它有別的事情做轉換吧:

devices.AddRange(from d in ae.UserDevices 
        select new DeviceInfo 
        { 
         DeviceGuid = d.DeviceID 
        } 

它使對象變得有點混亂,但使查詢中的Guid處理變得更加容易。