-
Notifications
You must be signed in to change notification settings - Fork 2
Home
Welcome to the Net.Http.WebApi.OData wiki!
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
.
To use it in your own Web API, firstly install the nuget package:
- OData 3.0 -
Install-Package Net.Http.WebApi.OData -version 3.5.0
- OData 4.0 -
Install-Package Net.Http.WebApi.OData -version 4.0.0
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Configure routes, etc
// Build the OData Entity Data Model
var entityDataModelBuilder = new EntityDataModelBuilder();
entityDataModelBuilder.RegisterEntitySet<Category>("Categories", x => x.Name);
entityDataModelBuilder.RegisterEntitySet<Product>("Products", x => x.Name);
entityDataModelBuilder.BuildModel();
}
}
Note that when you register an Entity Set, you also specify the name of the Entity Set. The name needs to match the URL you intend to use so if you use http://myservice/api/Products
then register the Entity Set using .RegisterEntitySet<Product>("Products");
, if you use http://myservice/api/Product
then register the Entity Set using .RegisterEntitySet<Product>("Product");
.
In your controller, define a Get method which accepts a single parameter of ODataQueryOptions
:
public IEnumerable<MyClass> Get(ODataQueryOptions queryOptions)
{
var validationSettings = new ODataValidationSettings { ... };
queryOptions.Validate(validationSettings);
// Implement query logic.
}
The ODataQueryOptions
class contains properties which can be interrogated to understand the specified query.