加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:21:00 所属栏目:百科 来源:网络整理
导读:我有一个LINQ to EF查询,它以类的形式返回数据.该课程有一个List RecipeCategories我需要填充的财产. RecipeCategories表是Recipe表和RecipeCategories表之间的关系表,可以是多对多.我找到了足够的信息来获取编译代码,但是它在运行时出错并且我无法弄清楚如
我有一个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();

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读