Introduction
In this post, we will learn about OData by using ASP.Net Web API 2 in MVC application.
What’s OData protocol?
The Open Data Protocol (OData) is a data access protocol for the web. OData provides a uniform way to query and manipulate data sets through CRUD operations (create, read, update, and delete).
Prerequisites
As I said earlier, we are going to use OData protocol in our MVC application. For this, you must have Visual Studio 2015 (.NET Framework 4.5.2) and SQL Server.
SQL Database part
Here, find the script to create database.
Create Database
Create your MVC application
Open Visual Studio and select File >> New Project.
The "New Project" window will pop up. Select ASP.NET Web Application (.NET Framework), name your project, and click OK.
Now, new dialog will pop up for selecting the template. We are going to choose Web API template and click OK.
Add a Model class
In Solution Explorer, right click on Models folder > Add > Class > Name your class.
Employee.cs
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations.Schema;
- using System.Linq;
- using System.Web;
-
- namespace WebAPIODataApp.Models
- {
- [Table("Employee")]
- public class Employee
- {
- public int EmployeeID { get; set; }
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string Gender { get; set; }
- public string Designation { get; set; }
- public int Salary { get; set; }
- public string City { get; set; }
- public string Country { get; set; }
-
-
- }
- }
Create a Controller
Now, we are going to create a Controller. Right click on the Controllers folder > Add > Controller> selecting Web API 2 OData v3 Controller with actions, using Entity Framework > click Add.
After clicking on Add button, window will pop up, as shown below.
We need to specify our Model class (in this case Employee.cs) and name for our Controller.
Finally, in order to add data context class, click on new data context > given a name for our new data context > Click Add.
The scaffolding adds two code files to the project.
- EmployeesController.cs - defines the Controller which implements the OData endpoint.
- EmployeeServContext.cs - ensures that our application is connected to the database.
EmployeesController.cs
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.Data.Entity;
- using System.Data.Entity.Infrastructure;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Threading.Tasks;
- using System.Web.Http;
- using System.Web.Http.ModelBinding;
- using System.Web.Http.OData;
- using System.Web.Http.OData.Routing;
- using WebAPIODataApp.Models;
-
- namespace WebAPIODataApp.Controllers
- {
-
- public class EmployeesController : ODataController
- {
- private EmployeeServContext db = new EmployeeServContext();
-
-
- [EnableQuery]
- public IQueryable<Employee> GetEmployees()
- {
- return db.Employees;
- }
-
- }
EmployeeServContext.cs
- using System;
- using System.Collections.Generic;
- using System.Data.Entity;
- using System.Linq;
- using System.Web;
-
- namespace WebAPIODataApp.Models
- {
- public class EmployeeServContext : DbContext
- {
-
-
-
-
-
-
-
- public EmployeeServContext() : base("name=EmployeeServContext")
- {
- }
-
- public System.Data.Entity.DbSet<WebAPIODataApp.Models.Employee> Employees { get; set; }
- }
- }
Add EDM and route
First of all, we need to add connection string.
In Solution Explorer, open web.config file and add inside configuration element in the following section.
- <connectionStrings>
- <add name="EmployeeServContext" connectionString="Data Source=.;Initial Catalog=EmployeeDB;Integrated Security=True" providerName="System.Data.SqlClient" />
- </connectionStrings>
Note - You must specify the connection string from EmployeeDB database which has been created above.
Next step is - In Solution Explorer, select App_Start > double click on WebApiConfig.cs, then we should add the following code to the register method:
- public static void Register(HttpConfiguration config)
- {
- ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
- builder.EntitySet<Employee>("Employees");
- config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());
-
- }
Explanation - Register method ensures two things,
- Creates an EDM (Entity Data Model).
- Adds a route for OData service.
The EDM is used to create the service metadata document. At this level, we have two possibilities by using,
- The ODataConventionModelBuilder class which creates an EDM by using default naming conventions.
- The ODataModelBuilder class to create the EDM by adding properties, keys, and navigation properties.
In the last, we need to call the MapOdataRoute extension method for routing. We can conclude that our URI for Employees EntitySet is http://localhost:56262/odata/Employees.
Note - When you run our URI first time, the database table will be created as follow. Don’t forget add some records into Employee table for demo.
Consuming OData Service
In order to consume OData service, we will work to display data by using jqxGrid plugin.
Let’s GO.
Create controller
Now, we are going to create a controller. Right click on the controllers folder > Add > Controller> selecting MVC 5 Controller – Empty > click Add.
HomeController.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace WebAPIODataApp.Controllers
- {
- public class HomeController : Controller
- {
- public ActionResult Index()
- {
-
- return View();
- }
- }
- }
Adding View
In HomeController, just right click on Index() action, select Add View and window will pop up. Write a name for your View. Finally, click Add.
Index cshtml
- @{
- ViewBag.Title = "Data Employees";
- }
-
- <h2> Data Employees </h2>
-
- <div id="gridEmployee" style="margin:20px auto;"></div>
-
- @section scripts {
-
-
- <script type="text/javascript" src="http://jqwidgets.com/jquery-widgets-demo/scripts/jquery-1.11.1.min.js"></script>
-
- <script type="text/javascript" src="http://jqwidgets.com/jquery-widgets-demo/jqwidgets/jqx-all.js"></script>
-
- <link rel="stylesheet" type="text/css" href="http://jqwidgets.com/jquery-widgets-demo/jqwidgets/styles/jqx.base.css" />
-
- <script type="text/javascript">
-
- $(document).ready(function () {
-
-
- var source =
- {
- datatype: "json",
-
-
- datafields: [
-
- { name: 'EmployeeID', type: 'number' },
- { name: 'FirstName', type: 'string' },
- { name: 'LastName', type: 'string' },
- { name: 'Gender', type: 'string' },
- { name: 'Designation', type: 'string' },
- { name: 'Salary', type: 'number' },
- { name: 'City', type: 'string' },
- { name: 'Country', type: 'string' }
-
- ],
-
- url: '/odata/Employees'
- };
-
- var dataAdapter = new $.jqx.dataAdapter(source);
-
-
- $("#gridEmployee").jqxGrid(
- {
- width: 800,
- source: dataAdapter,
- pageable: true,
- sortable: true,
-
- columns: [
-
- { text: "Employee ID", datafield: "EmployeeID" },
- { text: "FirstName", datafield: "FirstName" },
- { text: "LastName", datafield: "LastName" },
- { text: "Gender", datafield: "Gender" },
- { text: "Designation", datafield: "Designation" },
- { text: "Salary", datafield: "Salary" },
- { text: "City", datafield: "City" },
- { text: "Country", datafield: "Country" }
-
- ]
- });
- });
- </script>
- }
Output - That’s all. Please send your feedback and queries in comments box.