使用LINQ外部联接结果填充模型

时间:2013-05-12 21:00:53

标签: c# .net linq

我正在尝试使用LINQ外连接的结果填充模型,但是我收到以下错误:无法将匿名IEnemerable隐式转换为列表。

我有以下型号:

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 个答案:

答案 0 :(得分: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();