C# 实体框架排序包括

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15378136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:33:39  来源:igfitidea点击:

Entity Framework Ordering Includes

c#linqentity-frameworkentity-framework-5

提问by Serj Sagan

I am trying to get something like the following to work:

我正在尝试使以下内容起作用:

_dbmsParentSections = FactoryTools.Factory.PdfSections
                        .Include(x => x.Children.OrderBy(y => y.Order).ToList())
                        .Include(x => x.Hint).Include(x => x.Fields)
                        .Where(x => x.FormId == FormId && x.Parent == null)
                        .OrderBy(o => o.Order)
                        .ToList();

The part that causes the exception is:

导致异常的部分是:

.Include(x => x.Children.OrderBy(y => y.Order).ToList())

EDIT:

编辑:

Upon further observation,

经过进一步观察,

_dbmsParentSections.ForEach(x => x.Children = x.Children.OrderBy(y => y.Order).ToList());

did the job for me (after the initial Factorycall and without the Children.OrderBy).

为我完成了这项工作(在最初的Factory电话之后并且没有Children.OrderBy)。

采纳答案by Olav Nyb?

It seems you cannot sort the children collection in your query. Either sort after the query or load the children in a second query.

您似乎无法对查询中的 children 集合进行排序。在查询后排序或在第二个查询中加载子项。

Similar question and answer here

类似的问题和答案在这里

回答by Peter Kiss

This will never gona work. EF include is try to understand and translate everything to SQL, but you want to much from this. Load all entities without sorting and .ToList()-ing, and write an extension method for IEnumerable to get an ordered result.

这永远不会奏效。EF include 试图理解所有内容并将其转换为 SQL,但您希望从中获得更多。加载所有实体,无需排序和 .ToList()-ing,为 IEnumerable 编写扩展方法以获得有序结果。

回答by Gert Arnold

The extension method Includeis a mere wrapper around DbQuery.Include. Internally it does not executethe expressions but only parsesthem, i.e. it takes their member expressions and converts them to a path as string. The path is used as input for DbQuery.Include.

扩展方法Include只是围绕DbQuery.Include. 在内部,它不执行表达式而只解析它们,即它接受它们的成员表达式并将它们作为字符串转换为路径。该路径用作 的输入DbQuery.Include

It has been requested before to enhance the functionality of Include, e.g. to allow partly loaded collections by including a Whereclause. Ordering could be another change request. But as you see, because of the internal working of Includethe whole mechanism will have to be re-engineered to implement such enhancements. I don't see it on the current road mapso it may take a while...

之前曾要求增强 的功能Include,例如通过包含Where子句来允许部分加载的集合。订购可能是另一个变更请求。但如您所见,由于Include整个机制的内部工作,必须重新设计以实现此类增强功能。我在当前的路线图上没有看到它,所以可能需要一段时间......

回答by user6314169

You should not convert an IQueryabletype to IEnumerableand call Includebecause Includeis not supported by IEnumerabletype.

您不应该将IQueryable类型转换为IEnumerable和调用,Include因为类型Include不支持IEnumerable

In short, never call Include after ToList

简而言之,永远不要在之后调用 Include ToList

IQueryable = server side call (SQL)
IEnumerable = client side (loaded in memory)

回答by Charles Owen

Generally if you're using a bunch of includes, it's because you need to access child properties in a view. What I do is order the child collection when I need to access it in a view.

通常,如果您使用一堆包含,那是因为您需要访问视图中的子属性。当我需要在视图中访问它时,我所做的是订购子集合。

For example, I might build some Include statements for a master/detail form. There's no sense ordering this at the initial EF query. Instead, why not order these child records at the view level when you're actually accessing them?

例如,我可能会为主/详细信息表单构建一些 Include 语句。在初始 EF 查询中对此进行排序是没有意义的。相反,当您实际访问它们时,为什么不在视图级别对这些子记录进行排序?

I might have a survey with multiple survey questions. If I want to present the questions in a particular order at do it at the partial view level when I'm passing the model child collection to the partial view.

我可能有一个包含多个调查问题的调查。如果我想在将模型子集合传递给局部视图时在局部视图级别以特定顺序呈现问题。

@Html.Partial("_ResponsesPartial",Model.SurveyResponses.OrderBy(x => 
x.QuestionId))

回答by FRL

I use this code por order the include, using a select and a function to order the collection. Is not the best but work fine if subcollection is small

我使用此代码来订购包含,使用选择和函数来订购集合。不是最好的,但如果子集合很小,则工作正常

   // GET: api/Tareas
    [HttpGet]
    public IEnumerable<Tarea> GetTareas()
    {
        var result = _context.Tareas
            .Include(p => p.SubTareas)
            .Select(p => SortInclude(p));
        return result;
    }

    private Tarea SortInclude(Tarea p)
    {
        p.SubTareas = (p.SubTareas as HashSet<SubTarea>)?
            .OrderBy(s => s.Position)
            .ToHashSet<SubTarea>();
        return p;
    }

回答by Иво Недев

Depending on the use case you might not need to load in separate query or sort afterwards.

根据用例,您可能不需要加载单独的查询或之后进行排序。

In my case I needed them ordered for when looping in the view so I just ordered there

在我的情况下,我需要在视图中循环时订购它们,所以我只是在那里订购

@foreach (var subObject in Object.SubObjects.OrderBy(x=>x.Order))