Entity Framework Ordering Includes

前端 未结 7 1355
孤城傲影
孤城傲影 2020-11-27 21:11

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

_dbmsParentSections = FactoryTools.Factory.PdfSections
                        .Include(x => x.Ch         


        
相关标签:
7条回答
  • 2020-11-27 21:45

    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))
    
    0 讨论(0)
  • 2020-11-27 21:46

    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?

    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))
    
    0 讨论(0)
  • 2020-11-27 21:49

    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.

    0 讨论(0)
  • 2020-11-27 21:50

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

    Similar question and answer here

    0 讨论(0)
  • 2020-11-27 21:57

    You should not convert an IQueryable type to IEnumerable and call Include because Include is not supported by IEnumerable type.

    In short, never call Include after ToList

    IQueryable = server side call (SQL)
    IEnumerable = client side (loaded in memory)
    
    0 讨论(0)
  • 2020-11-27 21:58

    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;
        }
    
    0 讨论(0)
提交回复
热议问题