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

asp.net-mvc asp.net-mvc-3 c# entity-framework linq

Question

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)
1
11
8/1/2013 2:32:37 PM

Accepted 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?

20
12/13/2011 9:45:46 PM

Popular Answer

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow