Browse Source

Fix order by

pull/8411/head
Halil İbrahim Kalkan 6 years ago
parent
commit
be656d7ea9
  1. 28
      docs/en/Tutorials/Part-10.md

28
docs/en/Tutorials/Part-10.md

@ -326,6 +326,7 @@ Open the `BookAppService` interface in the `Books` folder of the `Acme.BookStore
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks; using System.Threading.Tasks;
using Acme.BookStore.Authors; using Acme.BookStore.Authors;
using Acme.BookStore.Permissions; using Acme.BookStore.Permissions;
@ -387,23 +388,17 @@ namespace Acme.BookStore.Books
public override async Task<PagedResultDto<BookDto>> GetListAsync(PagedAndSortedResultRequestDto input) public override async Task<PagedResultDto<BookDto>> GetListAsync(PagedAndSortedResultRequestDto input)
{ {
//Set a default sorting, if not provided
if (input.Sorting.IsNullOrWhiteSpace())
{
input.Sorting = nameof(Book.Name);
}
//Get the IQueryable<Book> from the repository //Get the IQueryable<Book> from the repository
var queryable = await Repository.GetQueryableAsync(); var queryable = await Repository.GetQueryableAsync();
//Prepare a query to join books and authors //Prepare a query to join books and authors
var query = from book in queryable var query = from book in queryable
join author in _authorRepository on book.AuthorId equals author.Id join author in _authorRepository on book.AuthorId equals author.Id
orderby input.Sorting //TODO: Can not sort like that!
select new {book, author}; select new {book, author};
//Paging //Paging
query = query query = query
.OrderBy(NormalizeSorting(input.Sorting))
.Skip(input.SkipCount) .Skip(input.SkipCount)
.Take(input.MaxResultCount); .Take(input.MaxResultCount);
@ -435,6 +430,25 @@ namespace Acme.BookStore.Books
ObjectMapper.Map<List<Author>, List<AuthorLookupDto>>(authors) ObjectMapper.Map<List<Author>, List<AuthorLookupDto>>(authors)
); );
} }
private static string NormalizeSorting(string sorting)
{
if (sorting.IsNullOrEmpty())
{
return $"book.{nameof(Book.Name)}";
}
if (sorting.Contains("authorName", StringComparison.OrdinalIgnoreCase))
{
return sorting.Replace(
"authorName",
"author.Name",
StringComparison.OrdinalIgnoreCase
);
}
return $"book.{sorting}";
}
} }
} }
``` ```

Loading…
Cancel
Save