Alex Rivera | Logout

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

Asked 2011-12-13T21:30:58.310
11

I'm trying to populate a dropdown in my view. Any help is greatly appreciated. Thanks.

Error:

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

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

Controller:

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

View:

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

1 Answer

5

You can cast your query to an .AsEnumerable() prior to the conversion to force it to use Linq to Objects for the casting but it is better to use the SQL compatible functions available in System.Data.Objects.SqlClient.SqlFunctions like so:

(from c in new IntraEntities().CategoryItems
select new SelectListItem() { 
    Text = c.Name, 
    Value = SqlFunctions.StringConvert((double)c.ID).TrimStart() 
})
answered 2012-09-07T15:27:30.773

Your Answer