Introduction

This article explains how to use $select in ASP.NET Web API OData. Here we install the ASP.NET Web API2 OData Package. By using the $select we can find specified data from the controller.

$select: By using this query an option is provided to the user for selecting the desired set of information. It decides what field is to be returned to the user. When we use the $select operator it allows the user to create the subset of the entities and selects that paricualr set of data.

Let's see an example.

Step 1

Create an application using the Web API 2.

Step 2

Add a Model Class.

Add the following code:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. namespace WebApplication3.Models
  6. {
  7. public class Student
  8. {
  9. public int ID { get; set; }
  10. public string Name { get; set; }
  11. public string Address { get; set; }
  12. public int Marks { get; set; }
  13. }
  14. }

Step 3

Install the "ASP.NET WebAPI2 OData" package.

Step 4

Create a Web API2 Controller.

Add the following code:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Http;
  6. using System.Web.Http;
  7. using System.Web.Http.OData.Query;
  8. using WebApplication3.Models;
  9. namespace WebApplication3.Controllers
  10. {
  11. public class StudentsController : ApiController
  12. {
  13. Student[] student = new Student[]
  14. {
  15. new Student{ID=1,Name="Student1",Address="Address1",Marks=34},
  16. new Student {ID=2,Name="Student2",Address="Address2",Marks=67},
  17. new Student {ID=3,Name="Student3",Address="Address3",Marks=89},
  18. new Student {ID=4,Name="Student4",Address="Address3",Marks=90}
  19. };
  20. // GET api/values
  21. [Queryable()]
  22. public IEnumerable<Student>Get()
  23. {
  24. return student;
  25. }
  26. }
  27. }

Step 5

Now execute the application and copy the URL.

Copy the port fom here

Then open Fiddler.

It selects only the ID and Name of the Student.