Building OData Services With ASP.NET Web API-Part1

Open Visual Studio 2012 >> File >> New >> Project >> Select ASP.NET MVC4 Web Application Template >> Select Web API Template
1
2
It will add automatically OData dependencies for us.Also you can install OData dependencies by using Nuget as well.
3

Create a new controller named CustomersController by rightclicking the Controller folder.
9

 

 

 

 

Then add new class named Customer in the Model folder and add some properties like below
4
Also add one more folder named Domain and add a class named CustomerDataContext, It contains a method Customers which return some customers informations.
5

For setting the OData first i need to do is set up my routing that can be get in to the Customers controller based on OData routing scheme not traditional web api routing schemes.Go to the WebApiConfig class in the App_Start folder and add a helper method GetImplicitEdm for defining entity data model.
6
This method will return IEdmModel which is a interface abstraction on the top of entity data models.ODataModelBuilder class will create set most of the entity data models automatically for you.The main thing you tell to the builder is entity sets are involved and then call the GetEdmModel method associated with the builder class,this will find all the properties on the object,find the types of those properties,look for navigation properties relates other objects in the model. Also add one more route (marked as yellow above) other than the web api route by calling the extension method MapODataRoute which accepts the parameters such as name of the route,a route prefix similar to the api route prefix in the default web api route and then call our helper method GetImplicitEdm.
Then the next step is go to the customers controller and change our base class ApiController to EntitySetController which is generic type takes two arguments,first one is the type of the entity controller represents and second one is the type of key property in that customer object and override Get method of type IQueryble and return our Customers.
8

Run the application and browse the url like below.It will return all the customers.

10

Then i am going to take individual customers. To do that there is a separate override base class called GetEntityByKey and querying by using linq.Note that this is a protected method it expose the service operation is actually a different public method on our base class and the public method will call this one.
11

Go and run the application and browse the url like below.It will return the customer with name “Jameel”

12

Enjoy reading…