Skip to content

Commit 38224c9

Browse files
committed
Follow-up to Dmitry's patch for NH-2566: Make the rewrite more cautious by only doing it if the result operators in the outer query are identified as compatible for this procedure. Also add a test case more similar to the one in the bug report, plus with an order-by clause to test this likely combination.
1 parent 688d00f commit 38224c9

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

src/NHibernate.Test/Linq/ByMethod/GroupByTests.cs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,24 @@ public void GroupByAndTake()
254254
Assert.That(names.Count, Is.EqualTo(3));
255255
}
256256

257+
258+
[Test]
259+
public void GroupByAndTake2()
260+
{
261+
//NH-2566
262+
var results = (from o in db.Orders
263+
group o by o.Customer
264+
into g
265+
select g.Key.CustomerId)
266+
.OrderBy(customerId => customerId)
267+
.Skip(10)
268+
.Take(10)
269+
.ToList();
270+
271+
Assert.That(results.Count, Is.EqualTo(10));
272+
}
273+
274+
257275
private static void CheckGrouping<TKey, TElement>(IEnumerable<IGrouping<TKey, TElement>> groupedItems, Func<TElement, TKey> groupBy)
258276
{
259277
var used = new HashSet<object>();

src/NHibernate/Linq/GroupBy/AggregatingGroupByRewriter.cs

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,11 +42,25 @@ public static void ReWrite(QueryModel queryModel)
4242
}
4343
}
4444

45+
46+
private static readonly System.Type[] AcceptableOuterResultOperators = new[]
47+
{
48+
typeof (SkipResultOperator),
49+
typeof (TakeResultOperator),
50+
};
51+
52+
4553
private static void FlattenSubQuery(SubQueryExpression subQueryExpression, QueryModel queryModel)
4654
{
47-
var groupBy = (GroupResultOperator) subQueryExpression.QueryModel.ResultOperators[0];
55+
foreach (var resultOperator in queryModel.ResultOperators)
56+
{
57+
if (!AcceptableOuterResultOperators.Contains(resultOperator.GetType()))
58+
throw new NotImplementedException("Cannot use group by with the "
59+
+ resultOperator.GetType().Name + " result operator.");
60+
}
4861

49-
// Move the result operator up
62+
// Move the result operator up.
63+
var groupBy = (GroupResultOperator) subQueryExpression.QueryModel.ResultOperators[0];
5064
queryModel.ResultOperators.Insert(0, groupBy);
5165

5266
for (int i = 0; i < queryModel.BodyClauses.Count; i++)

0 commit comments

Comments
 (0)