2023-10-29

Entity Framework Core: how to combine selects and retain order?

What I currently want to achieve is this, but as IQueryable without the need of allocating the result to memory, as the request itself already contains pagination information. I am really not getting my head around it how to solve it, I already tried Union, but that does not retain any order at all.

Basically I want to order the items based on the State and the Updated properties. That's all one table and base.OnQuery returns the DbSet<HKTDownload>. Is it somehow possible to solve that only by OrderBy? If so, how?

    var list = new List<HKTDownload>();
    list.AddRange(
        base.OnQuery(context, request)
            .Where(x => 
                x.State == HKTDownloadState.DownloadContent
             || x.State == HKTDownloadState.Unpack
             || x.State == HKTDownloadState.Repair
             || x.State == HKTDownloadState.MoveFiles)
            .OrderByDescending(x => x.Updated)
            .Include(x => x.DownloadConfig)
    );
    list.AddRange(
        base.OnQuery(context, request)
            .Where(x => x.State == HKTDownloadState.DownloadNZBFile)
            .OrderByDescending(x => x.Updated)
            .Include(x => x.DownloadConfig)
    );
    list.AddRange(
        base.OnQuery(context, request)
            .Where(x => x.State == HKTDownloadState.QueuedForDownloadContent)
            .OrderByDescending(x => x.Updated)
            .Include(x => x.DownloadConfig)
    );
    list.AddRange(
        base.OnQuery(context, request)
            .Where(x => x.State == HKTDownloadState.Queued)
            .OrderByDescending(x => x.Updated)
            .Include(x => x.DownloadConfig)
    );
    list.AddRange(
        base.OnQuery(context, request)
            .Where(x => 
                x.State == HKTDownloadState.Completed 
                || x.State == HKTDownloadState.Error)
            .OrderByDescending(x => x.Updated)
            .Take(200)
            .Include(x => x.DownloadConfig)
    );
    
    return list.AsQueryable();


No comments:

Post a Comment