C# – LINQ to Entities only supports casting Entity Data Model primitive types

asp.net-mvcasp.net-mvc-3centity-frameworklinq

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)

Best Answer

How about this:

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

and how about using strongly typed view models instead of some weakly typed crap of a ViewBag (it's the way I call it)?

Like this:

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

then:

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);
}

and finally in your strongly typed view:

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

Much better, don't you think?

Related Topic