alexandre-spieser / mongodb-generic-repository

An example of generic repository implementation using the MongoDB C# Sharp 2.0 driver (async)
MIT License
311 stars 84 forks source link

GetPaginated does not seem to allow for sorting #13

Closed hiredgunhouse closed 5 years ago

hiredgunhouse commented 5 years ago

It seems that GetPaginated allows only for filtering but not sorting which kinda makes it unusable for typical grid case :/

alexandre-spieser commented 5 years ago

Hi, yeah you're right. I have prototyped it already but it's untested. Try this:

        /// <summary>
        /// Asynchronously returns a paginated list of the documents matching the filter condition.
        /// </summary>
        /// <typeparam name="TDocument">The type representing a Document.</typeparam>
        /// <param name="filter">A LINQ expression filter.</param>
        /// <param name="sortSelector">The property selector.</param>
        /// <param name="ascending">Order of the sorting.</param>
        /// <param name="skipNumber">The number of documents you want to skip. Default value is 0.</param>
        /// <param name="takeNumber">The number of documents you want to take. Default value is 50.</param>
        /// <param name="partitionKey">An optional partition key.</param>
        public virtual async Task<List<TDocument>> GetSortedPaginatedAsync<TDocument>(
            Expression<Func<TDocument, bool>> filter,
            Expression<Func<TDocument, object>> sortSelector,
            bool ascending = true,
            int skipNumber = 0,
            int takeNumber = 50,
            string partitionKey = null)
            where TDocument : IDocument
        {
            var sorting = ascending
                ? Builders<TDocument>.Sort.Ascending(sortSelector)
                : Builders<TDocument>.Sort.Descending(sortSelector);

            return await HandlePartitioned<TDocument>(partitionKey)
                    .Find(filter)
                    .Sort(sorting)
                    .Skip(skipNumber)
                    .Limit(takeNumber)
                    .ToListAsync();
        }

As you can see quite a few extra params are needed. I might create a class called PaginationOptions to reduce the number of params.

hiredgunhouse commented 5 years ago

Looks good, except for a scenario where you want to sort by multiple columns. I believe Builders.Sort has a Combine method that can combine multiple sort definitions at least that's what I used. Probably it would be best to provide an overload that takes SortDefinition and show in the docs that you can use that for both single and multiple column sorting scenarios. Also an overload taking PaginationOptions sounds good.

BTW. Thank you for your fantastic work it saved me a ton of time!

alexandre-spieser commented 5 years ago

Done. https://github.com/alexandre-spieser/mongodb-generic-repository/releases/tag/1.3.9