Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 871
Ber53rker Avatar asked Dec 13 '11 21:12

Ber53rker


2 Answers

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() 
})
like image 132
3 revs Avatar answered Oct 14 '22 16:10

3 revs


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?

like image 24
Darin Dimitrov Avatar answered Oct 14 '22 17:10

Darin Dimitrov