2013-05-12 51 views
1

我試圖用LINQ外部連接的結果填充模型,但出現以下錯誤:無法將匿名IEnemerable隱式轉換爲列表。使用LINQ外部連接結果填充模型

我有以下型號:

public class adminEditProductsPricelistProductsVM 
{ 
    public Product product { get; set; } // will be populated from Products table 
    public PricelistProduct pricelistProduct { get; set; } // will be populated from PricelistProducts table 
} 

這是查詢:

adminEditPricelistVM.adminEditProductsPricelistProductsVMs = 
      from product in products 
      join pricelistProduct in pricelistProducts 
      on product.ProductId equals pricelistProduct.ProductId into gj 
      from subpricelistProduct in gj.DefaultIfEmpty() 
      select new { product.Name }; 

什麼是正確的方式做到這一點嗎?

回答

1

您正嘗試將匿名類型的枚舉轉換爲不適用的adminEditProductsPricelistProductsVM類型的列表。您需要類似以下內容:

adminEditPricelistVM.adminEditProductsPricelistProductsVMs = 
       (from product in products 
       join pricelistProduct in pricelistProducts 
        on product.ProductId equals pricelistProduct.ProductId into gj 
       from subpricelistProduct in gj.DefaultIfEmpty() 
       select new adminEditProductsPricelistProductsVM() 
       { 
        Product = product, 
        PricelistProduct = subpricelistProduct 
       }).ToList(); 
+0

謝謝!然而PricelistProduct = pricelistProduct給了我一個「在當前上下文中不存在」的錯誤。應該是PricelistProduct = subprricistProduct? – 2013-05-12 21:14:25

+0

是的,它需要'subpricelistProduct' – Magnus 2013-05-12 21:23:27

+0

真棒謝謝! – 2013-05-12 21:41:58