2012-04-02 72 views
2

我我的产品表绑定到网格这样的LINQ to SQL无法转换对象

动作控制器

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

查看

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

,一切工作正常。但我需要从表中选择两个字段,我试图使用下面的代码

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

现在我得到下面的错误。也许有人可以解释这个问题很热?

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

回答

3

也许是这样的:

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

,然后改变这一点:

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