Skip to content
This repository has been archived by the owner on Dec 29, 2020. It is now read-only.
Trevor Pilley edited this page Mar 9, 2017 · 55 revisions

Welcome to the Net.Http.WebApi.OData wiki!

NuGet version

Net.Http.WebApi.OData is a C# library which parses an OData query uri into an object model which can be used to query custom data sources which are not IQueryable. It was extracted from the MicroLite.Extensions.WebApi library into a separate project so that it could be easily used by other projects.

Getting the OData Query Options

To use it in your own Web API, firstly install the nuget package Install-Package Net.Http.WebApi.OData and then in your controller, define a Get method which accepts a single parameter of ODataQueryOptions:

public IEnumerable<MyClass> Get(ODataQueryOptions queryOptions)
{
    // Implement query logic.
}

Using the OData Query Options

The ODataQueryOptions contains properties which can be interrogated to understand the specified query.

Consider the following OData query:

http://localhost/api/Customers?$select=FirstName,LastName,DateOfBirth&$orderby=LastName desc,FirstName

The ODataQueryOptions.Select would be as follows:

queryOptions.Select.RawValue;         // "$select=FirstName,LastName,DateOfBirth"
queryOptions.Select.Properties.Count; // 3
queryOptions.Select.Properties[0];    // "FirstName"
queryOptions.Select.Properties[1];    // "LastName"
queryOptions.Select.Properties[2];    // "DateOfBirth"

The ODataQueryOptions.OrderBy would be as follows:

queryOptions.OrderBy.RawValue;                // "$orderby=LastName desc,FirstName"
queryOptions.OrderBy.Properties.Count;        // 2

queryOptions.OrderBy.Properties[0].Direction; // OrderByDirection.Descending
queryOptions.OrderBy.Properties[0].Name;      // LastName
queryOptions.OrderBy.Properties[0].RawValue;  // "LastName desc"

queryOptions.OrderBy.Properties[1].Direction; // OrderByDirection.Ascending
queryOptions.OrderBy.Properties[1].Name;      // FirstName
queryOptions.OrderBy.Properties[1].RawValue;  // "FirstName"
Clone this wiki locally