Skip to content
This repository has been archived by the owner on Dec 29, 2020. It is now read-only.

Commit

Permalink
For #15
Browse files Browse the repository at this point in the history
Added $top
  • Loading branch information
TrevorPilley committed Nov 13, 2020
1 parent 8dac37c commit dcd6985
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
17 changes: 17 additions & 0 deletions Net.Http.OData.Tests/Linq/ODataQueryOptionsExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -308,5 +308,22 @@ public void ApplyTo_Throws_InvalidOperationException_For_Incorrect_QueryType()

Assert.Throws<InvalidOperationException>(() => queryOptions.ApplyTo(_categories.AsQueryable()));
}

[Fact]
public void ApplyTo_Top()
{
TestHelper.EnsureEDM();

var queryOptions = new ODataQueryOptions(
"?$top=4",
EntityDataModel.Current.EntitySets["Products"],
Mock.Of<IODataQueryOptionsValidator>());

IList<ExpandoObject> results = queryOptions.ApplyTo(_products.AsQueryable()).ToList();

Assert.Equal(4, results.Count);
Assert.Equal(_products[0].ProductId, ((dynamic)results[0]).ProductId);
Assert.Equal(_products[3].ProductId, ((dynamic)results[3]).ProductId);
}
}
}
20 changes: 19 additions & 1 deletion Net.Http.OData/Linq/ODataQueryOptionsExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -121,14 +121,32 @@ private static IEnumerable<ExpandoObject> ApplyToImpl(ODataQueryOptions queryOpt
{
IQueryable q = queryable
.ApplyOrder(queryOptions)
.ApplySkip(queryOptions);
.ApplySkip(queryOptions)
.ApplyTop(queryOptions);

foreach (object entity in q)
{
yield return BuildExpando(queryOptions, entity);
}
}

private static IQueryable ApplyTop(this IQueryable queryable, ODataQueryOptions queryOptions)
{
if (queryOptions.Top.HasValue)
{
MethodCallExpression skipCallExpression = Expression.Call(
typeof(Queryable),
"Take",
new Type[] { queryOptions.EntitySet.EdmType.ClrType },
queryable.Expression,
Expression.Constant(queryOptions.Top.Value));

return queryable.Provider.CreateQuery(skipCallExpression);
}

return queryable;
}

private static ExpandoObject BuildExpando(ODataQueryOptions queryOptions, object entity)
{
IEnumerable<PropertyPath> propertyPaths = queryOptions.Select?.PropertyPaths ?? queryOptions.EntitySet.EdmType.Properties.Where(p => !p.IsNavigable).Select(PropertyPath.For);
Expand Down

0 comments on commit dcd6985

Please sign in to comment.