本文將介紹嘗試在 LINQ 查詢中串連 int 和 string 類型的屬性時,遇到【Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting Entity Data Model primitive types】錯誤的解決方式。
今天跟 Kazuya 討論到在 LINQ 查詢中要串連 int 和 string 類型的屬性時,若是以下列程式碼來組合字串,會發生【Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting Entity Data Model primitive types.】的錯誤訊息。
1: using (NorthwindEntities context = new NorthwindEntities())
2: {
3: var query = from p in context.Regions
4: select new { col1 = p.RegionID + "、" + p.RegionDescription };
5: foreach (var item in query)
6: {
7: Response.Write(item.col1);
8: }
9: }
在網路上有人提到先將查詢結果轉成 List 後就可以順利組字串,改成下列的程式碼就可以了。
1: using (NorthwindEntities context = new NorthwindEntities())
2: {
3: var query = (from p in context.Regions
4: select p).ToList();
5: var result = from p in query
6: select new { col1 = p.RegionID + "、" + p.RegionDescription };
7:
8: foreach (var item in result)
9: {
10: Response.Write(item.col1);
11: }
12: }
執行結果如下:
【參考資料】