LINQ to Entities不支持指定的类型成员.仅支持初始值设定项,实体成员和实体导航属性

sam*_*a07 9 linq grid entity-framework asp.net-mvc-3

我花了两天时间想知道为什么这不起作用,但对于我的其他表格,它工作得非常好.我甚至测试了包含许多字段的其他模型.特别是这个,即使只有2个字段也不起作用.我知道我可能会错过一个明显的部分,请帮忙.

这是我的模特

public class ReceivedItem
{        
    public int ReceivedItemID { get; set; }
    public int ItemID { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

视图模型

public class ReceivedItemViewModel
 {
    public int ReceivedItemID { get; set; }
    public int ItemID { get; set; }
 }
Run Code Online (Sandbox Code Playgroud)

调节器

[GridAction]
public ActionResult GetReceivedItems()
  {
      return View(new GridModel(GetReceivedItemsViewModels()));
  }

private IQueryable<ReceivedItemViewModel> GetReceivedItemsViewModels()
{
    return db.ReceivedItems
         .Select(
          c => new ReceivedItemViewModel
            { 
               ItemID = c.ItemID
             });
 }
Run Code Online (Sandbox Code Playgroud)

视图

 @(Html.Telerik().Grid<ReceivedItem>()
.Name("grdItems")
.DataBinding(binding => binding.Ajax()
    .Select("GetReceivedItems", "Receiving"))
.DataKeys(keys => keys.Add(o => o.ItemID))
.Columns(cols =>
{  
    cols.Bound(c => c.ItemID);
})
.Pageable()
.Sortable()
.Groupable()
.Filterable()
Run Code Online (Sandbox Code Playgroud)

)

我使用firebug时出错:

The specified type member 'ReceivedItemID' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
Run Code Online (Sandbox Code Playgroud)

Ste*_*ves 12

据我所知,您无法在Linq-to-SQL查询中初始化非实体对象.尝试枚举结果,然后使用Linq创建视图模型.

你有什么(我猜这是抛出异常的地方):

// Original Code
return db.ReceivedItems
     .Select(
      c => new ReceivedItemViewModel
        { 
           ItemID = c.ItemID
         });
Run Code Online (Sandbox Code Playgroud)

枚举,然后使用Linq创建视图模型:

// First statement
var items = db.ReceivedItems.ToArray(); // Enumerates the collection.
// Second statement
return items.Select(
  c => new ReceivedItemViewModel
    { 
       ItemID = c.ItemID
     });
Run Code Online (Sandbox Code Playgroud)

第一个Linq语句被转换为SQL语句,结果返回并枚举为数组,最后,在第二个语句中,该数组用于创建视图模型的集合.使用原始语句,Linq语句的SQL转换必须考虑视图模型(它无法做到).

我希望这有帮助.(并且有道理):)