Linq中的错误 - 无法转换为存储表达式

时间:2017-10-18 15:53:11

标签: c# linq

我正在尝试运行Linq并抛出一个异常声明:

  

LINQ to Entities无法识别方法'System.Collections.Generic.List`1 [ECommerceApp.Models.CategoryList] CategoryDe​​tails()'方法,并且此方法无法转换为商店表达式。

以下是定义的类:

public class ProductDetails : Products
{
   public string ParentCatName { get; set; }
   public string ChildCatName { get; set; }
   public string ImagePath { get; set; }
   public List<CategoryList> Categories { get; set; }
}

public class CategoryList
{
   public string Category { get; set; }
   public string SubCategory { get; set; }
   public string ParentCategory { get; set; }
}

我要在主页中显示所有类别,因此,定义了类中的类别列表。以下是Linq

public ActionResult Index()
{
    var result = (from c in db.Products
                  select new ProductDetails
                  {
                     ProductName = c.ProductName,
                     Price = c.Price,
                     Categories = CategoryDetails() //Throws exception here and I tried to convert it to ToList() but doesn't work
                  }).ToList();

     return View(result);
}

public List<CategoryList> CategoryDetails()
{
    List<CategoryList> result = aGateway.GetAllCategories().ToList();
    return result;
}

最后,在视图中,我尝试使用foreach循环访问类别详细信息:

 @item.Categories[0].Category
 @item.Categories[0].SubCategory
 @item.Categories[0].ParentCategory

我有什么遗失的吗?

4 个答案:

答案 0 :(得分:1)

您的表达式的查询方面并不知道您可用的CategoryDetails()函数。

A similar issue with suggestions

答案 1 :(得分:1)

尝试在查询之外首先获取类别并将其存储在集合中,然后将集合分配给新创建的ProductDetails

public ActionResult Index()
{
    var cats = CategoryDetails();
    var result = (from c in db.Products
                  select new ProductDetails
                  {
                     ProductName = c.ProductName,
                     Price = c.Price,
                     Categories = cats 
                  }).ToList();

     return View(result);
}

public List<CategoryList> CategoryDetails()
{
    List<CategoryList> result = aGateway.GetAllCategories().ToList();
    return result;
}

答案 2 :(得分:1)

这样的事情应该有效:

  var result = (from c in db.Products
                  select new ProductDetails
                  {
                     ProductName = c.ProductName,
                     Price = c.Price,
                     Categories = null 
                  }).ToList();
 foreach (var c in result)
     {
       c.Categories= CategoryDetails();
     }
     return View(result);

如果这不起作用,请定义结果类,不要在linq查询中指定categories属性

答案 3 :(得分:1)

gnsanty回答有效,但如果您使用linq,则无需使用foreach语句:

var result = (from c in db.Products
              select new ProductDetails
              {
                 ProductName = c.ProductName,
                 Price = c.Price,
                 Categories = null 
              })
  .ToList()  // Execute the query before updating the property
  .Select(pd => {
    pd.Categories = CategoryDetails();
    return pd;
  })
  .ToList();