微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 以列表形式获取子集合

我有一个LINQ to EF查询,它以类的形式返回数据.该课程有一个List< RecipeCategories>我需要填充的财产. RecipeCategories表是Recipe表和RecipeCategories表之间的关系表,可以是多对多.我找到了足够的信息来获取编译代码,但是它在运行时出错并且我无法弄清楚如何正确实现.
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,RecipeCategories = r.RecipeCategories.Select(i => new RecipeCategoryItem { Id = i.ID,CategoryName = i.categoryName }).ToList()
              }).First();

这是我得到的错误.

LINQ to Entities does not recognize the method ‘System.Collections.Generic.List1[RecipeCategoryItem] ToList[RecipeCategoryItem](System.Collections.Generic.IEnumerable1[RecipeCategoryItem])’ method,and this method cannot be translated into a store expression.

我正在研究的部分是这一行.

RecipeCategories = r.RecipeCategories.Select(i => new RecipeCategoryItem { Id = i.ID,CategoryName = i.categoryName }).ToList()

RecipeCategories是List< RecipeCategoryItem>属性.

我正在尝试做什么,如果是这样,怎么样?

谢谢.

解决方法

你正在调用ToList里面变成一个更大的查询.删除对.ToList()的调用.

问题是查询中的所有内容都变成了一个大的表达式树,实体框架试图将其转换为sql语句.从sql的角度来看,“ToList”没有任何意义,因此不应在查询中的任何位置调用它.

在大多数情况下,您希望在返回整个查询之前调用ToList,以确保评估查询并将结果加载到内存中.在这种情况下,您只返回一个对象,因此对First的调用基本上是相同的.

RecipeCategories是List< RecipeCategoryItem&gt ;?有多重要?如果你可以改为IEnumerable,那么你可以毫无问题地删除对ToList的调用. 如果您有一个List是绝对必要的,那么您首先需要使用初始实体框架查询和匿名类型(不调用ToList)来获取所有信息,然后将您收到的数据转换为您想要的对象类型归还它. 或者您可以从多个查询中逐步构建RecipeInfo对象,如下所示:

var ri = (from r in recipeData.Recipes
            where r.ID == recipeId
            select new RecipeItem
            {
                Id = r.ID,}).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();

请注意,最后一个示例将导致两次数据库跳闸,但会导致更少的数据通过线路发送.

原文地址:https://www.jb51.cc/csharp/98260.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐