您在变成更大查询的内容中调用 ToList 。删除对 .ToList() 的调用。
问题是查询中的所有内容都会变成一个大表达式树,实体框架尝试将其转换为 SQL 语句。从 SQL 的角度来看,“ToList”没有任何意义,因此您不应在任何地方调用它inside您的查询。
在大多数情况下,您希望在返回整个查询之前调用 ToList,以确保计算查询并将结果加载到内存中。在这种情况下,您只返回一个对象,因此调用First
本质上做同样的事情。
RecipeCategories 是多么重要List<RecipeCategoryItem>
?如果您可以将其改为 IEnumerable,那么您可以删除对ToList
没有任何问题。
如果您绝对有必要拥有List
,那么您首先需要使用初始实体框架查询和匿名类型(不调用 ToList)提取所有信息,然后在返回之前将收到的数据转换为您想要的对象类型。
或者,您可以通过多个查询逐步构建 RecipeInfo 对象,如下所示:
var ri = (from r in recipeData.Recipes
where r.ID == recipeId
select new RecipeItem
{
Id = r.ID,
ProductId = r.Product.ID,
RecipeName = r.recipeName,
RecipeDescription = r.recipeDescription,
Servings = r.servings.HasValue ? r.servings.Value : 0,
CreatedDate = r.createdDate,
PrepTime = r.prepTime.HasValue ? r.servings.Value : 0,
CookTime = r.cookTime.HasValue ? r.servings.Value : 0,
Approved = r.approved,
RecipeInstructions = r.recipeInstructions,
RecipeIngredients = r.recipeIngredients,
}).First();
var rc = from c in recipeData.RecipeCategories
where c.Recipes.Any(r => r.ID == recipeId)
select new RecipeCategoryItem
{
Id = c.ID, CategoryName = c.categoryName
};
ri.RecipeCategories = ri.ToList();
请注意,最后一个示例将导致两次数据库访问,但会导致通过线路发送的数据较少。