2014-03-30 31 views
0

正如您所看到的,我在使用Kendo UI構建Data Gird時遇到了此錯誤。有人可以在我的代碼中指出我錯在哪裏。實體或複雜類型'AdventureWorks2012Model.Product'不能在LINQ to Entities查詢中構建

private IEnumerable<Product> GetSubProduct() 
     { 
      var context = new AdvenDBEntities(); 
      var subcate = context.Products.Select(p => new Product 
      { 
       ProductID = p.ProductID, 
       Name = p.Name, 
       Color = p.Color, 
       ListPrice = p.ListPrice, 
      }).ToList(); 

      return subcate; 
      } 

錯誤: The entity or complex type 'AdventureWorks2012Model.Product' cannot be constructed in a LINQ to Entities query. 謝謝你這麼多的時間!

+0

可能'Product'是模型中的實體,嘗試創建匿名類型對象。 – sallushan

回答

1

由於Product是模型的實體,您在創建新實體的同時選擇記錄,這不是一個好主意,我不知道模型如何處理這種行爲,這就是爲什麼它阻止你這樣做,(我猜)。反正你可以更改代碼這一點,

private IEnumerable<Product> GetSubProduct() 
{ 
    var context = new AdvenDBEntities(); 
    var subcate = context.Products.ToList(); 

    return subcate; 
} 

BTW你的函數名,指示你缺少一個Where條款。

您也可以創建一些自定義的DTO類並使用它。

E.g.

class ProductDTO 
{ 
    public int ProductID { get; set; } 
    public string Name { get; set; } 
    public string Color { get; set; } 
    public decimal ListPrice { get; set; } 
} 

private IEnumerable<ProductDTO> GetSubProduct() 
{ 
    var context = new AdvenDBEntities(); 
    var subcate = context.Products.Select(p => new ProductDTO 
         { 
          ProductID = p.ProductID, 
          Name = p.Name, 
          Color = p.Color, 
          ListPrice = p.ListPrice, 
         }).ToList(); 

    return subcate; 
} 
+0

這正是我想要的,我錯過了創建一個剛纔提到的新的ViewModel'ProductDTO'。謝謝,@sallushan! –

0

我可以爲您指出第一個難聞的氣味代碼。 DBContext implements IDisposable所以你要負責打電話給配置就可以了。在所有的,但在這裏一個情況下,使用塊

你必須建立查詢來獲取所有的產品,然後從中提取。

private IEnumerable<Product> GetSubProduct() 
{ 
     using (var context = new AdvenDBEntities()) 
     { 
       // Get all constructed type product and then select from it 
       var subcate = context.Products 
       .ToList()  
       .Select(p => new Product 
       { 
       ProductID = p.ProductID, 
       Name = p.Name, 
       Color = p.Color, 
       ListPrice = p.ListPrice, 
       }); 

       return subcate; 
     } 
} 
相關問題