Can we control LINQ expression order with Skip(), Take() and OrderBy()

后端 未结 6 782
日久生厌
日久生厌 2021-02-08 14:16

I\'m using LINQ to Entities to display paged results. But I\'m having issues with the combination of Skip(), Take() and OrderBy() calls.

6条回答
  •  太阳男子
    2021-02-08 15:01

    My workaround solution

    I've managed to workaround this problem. Don't get me wrong here. I haven't solved precedence issue as of yet, but I've mitigated it.

    What I did?

    This is the code I've used until I get an answer from Devart. If they won't be able to overcome this issue I'll have to use this code in the end.

    // get ordered list of IDs
    List ids = ctx.MyEntitySet
        .Include(/* Related entity set that is needed in where clause */)
        .Where(/* filter */)
        .OrderByDescending(e => e.ChangedDate)
        .Select(e => e.Id)
        .ToList();
    
    // get total count
    int total = ids.Count;
    
    if (total > 0)
    {
        // get a single page of results
        List result = ctx.MyEntitySet
            .Include(/* related entity set (as described above) */)
            .Include(/* additional entity set that's neede in end results */)
            .Where(string.Format("it.Id in {{{0}}}", string.Join(",", ids.ConvertAll(id => id.ToString()).Skip(pageSize * currentPageIndex).Take(pageSize).ToArray())))
            .OrderByDescending(e => e.ChangedOn)
            .ToList();
    }
    

    First of all I'm getting ordered IDs of my entities. Getting only IDs is well performant even with larger set of data. MySql query is quite simple and performs really well. In the second part I partition these IDs and use them to get actual entity instances.

    Thinking of it, this should perform even better than the way I was doing it at the beginning (as described in my question), because getting total count is much much quicker due to simplified query. The second part is practically very very similar, except that my entities are returned rather by their IDs instead of partitioned using Skip and Take...

    Hopefully someone may find this solution helpful.

提交回复
热议问题