A controller is a class that handles HTTP requests. You create a separate controller for each entity set in your OData service. In this tutorial, you will create one controller, for the Product entity.
In Solution Explorer, right-click the Controllers folder and select Add > Class. Name the class ProductsController.
The version of this tutorial for OData v3 uses the Add Controller scaffolding. Currently, there is no scaffolding for OData v4.
Replace the boilerplate code in ProductsController.cs with the following.
using ProductService.Models;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.OData;
namespace ProductService.Controllers
{
public class ProductsController : ODataController
{
ProductsContext db = new ProductsContext();
private bool ProductExists(int key)
{
return db.Products.Any(p => p.Id == key);
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
The controller uses the ProductsContext class to access the database using EF. Notice that the controller overrides the Dispose method to dispose of the ProductsContext.
This is the starting point for the controller. Next, we'll add methods for all of the CRUD operations.