Tomas
Tomas

Reputation: 18117

Linq to SQL Unable to cast object

I am binding my Product table to Grid like this

Action Controller

ViewData["Products"] = _repository.GetProducts(true);

View

@(Html.Telerik().Grid((IEnumerable<Product>)ViewData["Products"])

And everything works fine. But I need to select two fields only from Table and I tried to use code below

ViewData["Products"] = _repository.GetProducts(true).Select(p => new
{
Id = p.Id,
Name = p.Name
});

and now I get error below. Maybe someone could explain hot to solve this problem?

Unable to cast object of type System.Data.Linq.DataQuery to type System.Collections.Generic.IEnumerable

Upvotes: 2

Views: 345

Answers (1)

Arion
Arion

Reputation: 31249

Maybe something like this:

ViewData["Products"] = _repository.GetProducts(true).Select(p =>  new 
KeyValuePair<int,string>
(
   p.Id,
   p.Name
)).ToList();

And then change this:

@(Html.Telerik().Grid((List<KeyValuePair<int,string>>)ViewData["Products"])

Upvotes: 3

Related Questions