-
Notifications
You must be signed in to change notification settings - Fork 2
Home
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:
PM> Install-Package Net.Http.WebApi.OData
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Build the OData Entity Data Model first
var entityDataModelBuilder = new EntityDataModelBuilder();
entityDataModelBuilder.RegisterEntitySet<Category>("Categories", x => x.Name);
entityDataModelBuilder.RegisterEntitySet<Product>("Products", x => x.Name);
entityDataModelBuilder.BuildModel();
// Use Attribute Mapping for the OData controllers
config.MapHttpAttributeRoutes();
}
}
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/odata/Products
then register the Entity Set using .RegisterEntitySet<Product>("Products");
, if you use http://myservice/odata/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.