Click here to Skip to main content
15,888,025 members
Articles / Web Development
Tip/Trick

Expose OData Endpoint in Web API/MVC

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
11 Aug 2014CPOL4 min read 26.7K   2   5   1
In this tip, we will learn to implement OData endpoint in Web API application.

Introduction

In today's IT industry, OData is one of the common buzzwords. People are talking about OData and OData services. What can OData do? And in which scenario it fits best? We will discuss them a little and then we will see how to expose the OData endpoints in our Web API application.

So, let's discuss what OData is. OData stands for Open Data protocol that was introduced by Microsoft in an open release context, then it was widely adapted by the industry. It provides an idea of uniform data access.

We know that today's IT world is on top of data, data may come from various sources and multiple ways and data will be valuable only if we can categorize it easily. Hence the idea of a uniform data access mechanism was created. The industry thought that data might come from multiple locations and multiple protocols but it would be great if we can access data uniformly from all platforms.

For example, an analyst wanted to get data from a Windows data marketplace and SQL Azure using the same mechanism, hence the concept of OData was created.

Another example of an OData endpoint is something like that. Let's think of an e-commerce organization sharing their data with a vendor and one vendor wants to get a report based on region by providing a region code where another wants to get a sales report by country by providing a country key. But surprisingly, all the data is stored in a single place or in technical terms, in a single table.

The problem is that if tomorrow another vendor demands another type of report by supplying another key, then it needs to add another function to serve the needs. This is the exact situation where OData can rescue us.

Ok, so we have learned the fundamental idea behind OData, now we will implement an OData endpoint in our Web API application. In this example, we have used Web API 2.0 to implement an OData service, so please ensure that you have installed the OData package in your application before executing this code.

Image 1

To implement OData service in Web API, we have to inherit our controller from OData Controller or we can inherit our controller from EntitySetController<tentity,tkey> </tentity,tkey><tentity,tkey>too. The reason is, EntitySetController is inherited from ODataController. Here is the inheritance hierarchy.

Image 2

Now, in this example, we have used Entity Framework to fetch data from database and here is the data model for this example.

Image 3

The data model is very simple, just we have only one Model called “UserMaster”. Now, we will implement OData endpoint in application.

Create OData Endpoint using OData Controller

As we discuss, we can inherit our controller from ODataController. In this example, OdataController is our OData controller and it has inherited from ODataController.

C#
public class OdataController : ODataController
    {
        ConnectionStrign _db = new ConnectionStrign();

        [EnableQuery]
        public IQueryable Get()
        {
            return _db.UserMaster.AsQueryable();
        }
    }

The implementation is very simple, just we are returning IQuerable of the model, so that client will be able to fire further query into the returned data. The Get() action is decorated with [EnableQuery] attribute.

Register OData Endpoint

This is the process where we will register the OData endpoint. Just open WebApiConfig.cs file of the application and modify accordingly.

C#
public static class WebApiConfig
    {
        private static IEdmModel GenerateEdmModel()
        {
            var builder = new ODataConventionModelBuilder();
            builder.EntitySet("Odata");
            return builder.GetEdmModel();
        }

        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();
     //Expose Odata route
            config.Routes.MapODataRoute("odata", "odata", GenerateEdmModel());

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

The GenerateEdmModel() function is to generate Edm matadata for OData service.

C#
private static IEdmModel GenerateEdmModel()
 {
            var builder = new ODataConventionModelBuilder();
            builder.EntitySet("Odata");
            return builder.GetEdmModel();
 }

We have used EntitySet function which will register an entity set as a part of the model and returns an object that can be used to configure the entity set. Fine, we have completed our OData setup, now we can consume the OData endpoint from client. In this example, I am using Fiddler as client. But one typical OData client could be anything like web browser, Other .NET application or JavaScript application, etc. In Fiddler, I am trying to access the below URL and we are seeing that the data has come from endpoint.

Image 4

As we discussed, EntitySetController class is derived from ODataController and so that we can use EntitySetController too to expose OData endpoint. Let’s take a look at the implementation.

Expose OData Endpoint using EntitySetController<TEntity, TKey>

The implementation is very similar to the ODataController class, only we are passing the parameters to EntitySetController generic class. The first parameter is the actual Model and the second parameter is the key of the model. In this example, the key property of the UserMaster model is integer type so that:

C#
public class UserEntityController : EntitySetController
    {
        ConnectionStrign _db = new ConnectionStrign();
        public override IQueryable Get()
        {
            return _db.UserMaster.AsQueryable();
        }
    }

We are passing “int” as second argument. It could be any data type depending on model. The all other settings will remain the same.

Conclusion

In this tip, we have learned to expose Odata endpoint in Web API. OData is helpful when the application doesn’t know the query of end client.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer DELL International
India India
I am software developer from INDIA. Beside my day to day development work, i like to learn new technologies to update myself. I am passionate blogger and author in various technical community including dotnetfunda.com , c-sharpcorner.com and codeproject. My area of interest is modern web technology in Microsoft stack. Visit to my personal blog here.

http://ctrlcvprogrammer.blogspot.in/

Comments and Discussions

 
GeneralQuestion Pin
MichelWilker12-Aug-14 11:26
MichelWilker12-Aug-14 11:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.