2011-12-13 43 views
10

我試圖在我的視圖中填充下拉菜單。任何幫助是極大的讚賞。謝謝。LINQ to Entities只支持投射實體數據模型原始類型?

錯誤:

Unable to cast the type 'System.Int32' to type 'System.Object'.

LINQ to Entities only supports casting Entity Data Model primitive types.

控制器:

ViewBag.category = (from c in new IntraEntities().CategoryItems 
        select new SelectListItem() {Text=c.Name, Value=""+c.ID }).ToList<SelectListItem>(); 

查看:

Category:<br />@Html.DropDownList("category", (List<SelectListItem>)ViewBag.category) 
+0

Linq to enitites不支持這些類型的轉換convert.Tostring()和convert.ToDatetime().. – 2011-12-13 21:48:28

回答

19

如何:

ViewBag.category = 
    from c in new IntraEntities().CategoryItems.ToList() 
    select new SelectListItem 
    { 
     Text = c.Name, 
     Value = c.ID.ToString() 
    }; 

以及如何使用強類型的視圖模型,而不是一些弱類型的ViewBag廢話(這是我稱之爲的方式)?

像這樣:

public class CategoryViewModel 
{ 
    public string CategoryId { get; set; } 
    public IEnumerable<SelectListItem> Categories { get; set; } 
} 

則:

public ActionResult Foo() 
{ 
    var model = new CategoryViewModel 
    { 
     Categories = 
      from c in new IntraEntities().CategoryItems.ToList() 
      select new SelectListItem 
      { 
       Text = c.Name, 
       Value = c.ID.ToString() 
      } 
    }; 
    return View(model); 
} 
在強類型視圖

最後:

@model CategoryViewModel 
@using (Html.BeginForm()) 
{ 
    @Html.DropDownListFor(x => x.CategoryId, Model.Categories) 
    <button type="submit">OK</button> 
} 

好多了,你不覺得嗎?

+9

@olivehour,不,我不需要更多的聲望。我只想看到人們停止使用ViewBag的這個廢話,並開始在他們的ASP.NET MVC應用程序中使用視圖模型。 – 2011-12-13 21:49:26

0
ViewBag.category = (from c in new IntraEntities().CategoryItems 
        select new SelectListItem {Text=c.Name, Value=c.ID.ToString()}) 
.ToList<SelectListItem>(); 
+0

沒有工作,但謝謝。 「LINQ to Entities不識別方法'System.String ToString()'方法,並且此方法不能轉換爲存儲表達式。」 – Ber53rker 2011-12-13 21:43:18

+0

對不起,Darin再次正確 - 您需要調用.ToList()來執行查詢。然後,LINQ to Objects將識別.ToString()調用。 – danludwig 2011-12-13 21:46:39

4

您可以在轉換之前將查詢強制轉換爲.AsEnumerable(),以強制它將Linq用於對象以進行強制轉換,但最好使用System.Data.Objects.SqlClient中可用的SQL兼容函數。 SqlFunctions像這樣:

(from c in new IntraEntities().CategoryItems 
select new SelectListItem() { 
    Text = c.Name, 
    Value = SqlFunctions.StringConvert((double)c.ID).TrimStart() 
}) 
0

錯誤說,你試圖連接字符串與整數值。這在linq查詢中是不可能的。 對於int轉換成字符串,就可以使用

SqlFunctions.StringConvert((decimal?)intProperty) 
0

您可以使用SQL函數這樣的轉換:

ViewBag.category = (from c in new IntraEntities().CategoryItems 
        select new SelectListItem() { 
Text=c.Name, 
Value=SqlFunctions.StringConvert((double) c.ID) }).ToList<SelectListItem>(); 

但不要忘了,包括這個命名空間,在你的文件的頂部:

using System.Data.Objects.SqlClient;

0

是的,你正試圖「用整數值連接字符串,這在linq查詢中是不可能的」,就像納蘭M建議的那樣。確保它是數據庫中您試圖獲取的列。對我來說就是這樣。我正在指定錯誤的列。我正在給班上打電話,因爲顯然有人爲那個房產做了一個班。如果您在Visual Studio中工作,則可以檢查數據庫並查看您正在調用的是什麼。這樣你可以回答這個問題:「我想要的列在哪裏?」在數據庫中。

相關問題