From 7a39d70a3e6a8b2d1f06cca77f7d1c2a06cb11ec Mon Sep 17 00:00:00 2001 From: David Lebee Date: Mon, 22 Oct 2018 22:08:27 -0500 Subject: [PATCH] sort fix. --- PoweredSoft.DynamicQuery.Test/SortTests.cs | 57 ++++++++++++++++++++ PoweredSoft.DynamicQuery/QueryHandlerBase.cs | 7 +++ 2 files changed, 64 insertions(+) diff --git a/PoweredSoft.DynamicQuery.Test/SortTests.cs b/PoweredSoft.DynamicQuery.Test/SortTests.cs index 39494f6..8d535ba 100644 --- a/PoweredSoft.DynamicQuery.Test/SortTests.cs +++ b/PoweredSoft.DynamicQuery.Test/SortTests.cs @@ -32,5 +32,62 @@ namespace PoweredSoft.DynamicQuery.Test Assert.Equal(shouldResult, result.Data); }); } + + [Fact] + public void MultiSort() + { + MockContextFactory.SeedAndTestContextFor("SortTests_MultiSort", TestSeeders.SimpleSeedScenario, ctx => + { + var shouldResult = ctx.Orders.OrderBy(t => t.Customer.FirstName).ThenBy(t => t.OrderNum).ToList(); + + // query handler that is empty should be the same as running to list. + var criteria = new QueryCriteria() + { + Sorts = new List() + { + new Sort("Customer.FirstName"), + new Sort("OrderNum") + } + }; + + var queryHandler = new QueryHandler(); + var result = queryHandler.Execute(ctx.Orders, criteria); + Assert.Equal(shouldResult, result.Data); + }); + } + + private class MockSortInterceptor : ISortInterceptor + { + public IEnumerable InterceptSort(IEnumerable sort) + { + if (sort.Count() == 1 && sort.First().Path == "OrderNumStr") + return new ISort[] { new Sort("OrderNum", false) }; + + return sort; + } + } + + [Fact] + public void SortInterceptor() + { + MockContextFactory.SeedAndTestContextFor("SortTests_SortInterceptor", TestSeeders.SimpleSeedScenario, ctx => + { + var shouldResult = ctx.Orders.OrderByDescending(t => t.OrderNum).ToList(); + + // query handler that is empty should be the same as running to list. + var criteria = new QueryCriteria() + { + Sorts = new List() + { + new Sort("OrderNumStr", false) + } + }; + + var queryHandler = new QueryHandler(); + queryHandler.AddInterceptor(new MockSortInterceptor()); + var result = queryHandler.Execute(ctx.Orders, criteria); + Assert.Equal(shouldResult, result.Data); + }); + } } } diff --git a/PoweredSoft.DynamicQuery/QueryHandlerBase.cs b/PoweredSoft.DynamicQuery/QueryHandlerBase.cs index 16e8a36..4109b88 100644 --- a/PoweredSoft.DynamicQuery/QueryHandlerBase.cs +++ b/PoweredSoft.DynamicQuery/QueryHandlerBase.cs @@ -68,11 +68,18 @@ namespace PoweredSoft.DynamicQuery return; } + bool isAppending = false; Criteria.Sorts.ForEach(sort => { var transformedSort = InterceptSort(sort); if (transformedSort.Count == 0) return; + + transformedSort.ForEach(ts => + { + CurrentQueryable = CurrentQueryable.OrderBy(ts.Path, ts.Ascending == false ? QueryOrderByDirection.Descending : QueryOrderByDirection.Ascending, isAppending); + isAppending = true; + }); }); }