Select only few columns from a table to map with Odata Select query on C# Web API

roshni gandhi 1 Reputation point
2020-12-25T10:42:06.213+00:00

We have a table in the database which has multiple columns. We only want a query which will return only requested columns. These requested columns will from Odata Select Query requested using C# Web API.
For Example, I have an EmployeeTable which has below structure in SQL

51233-image.png

And I am calling below sample API to get the results
http://domain/controller/method?Select=EmployeeID,EmployeeName

This query should get only above 2 columns from the database; in the current scenario - Database returns all the columns and Odata configurations in Web API filters out the response before returning it to the user
Please help with how to implement this in the database.

ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
293 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Vaibhav Chaudhari 38,576 Reputation points
    2020-12-25T13:34:37.88+00:00

    I am not aware of .Net but the OData query for select should be something like below. Dollar sign is required

    http://localhost/odata/Products?$select=Price,Name


    Please don't forget to Accept Answer and Up-vote if the response helped -- Vaibhav

    0 comments No comments

  2. Duane Arnold 3,211 Reputation points
    2021-01-24T20:29:56.797+00:00

  3. Gokhan Guleser 1 Reputation point
    2021-07-17T17:39:12.037+00:00

    Solution is simple. Odata behaves like this :

    if your controller returns an IEnumerable type => Odata filter your returned list results (in this scenario possibly a list created by all selected columns from db)
    if your controller returns IQueryable => Odata selects only requested columns from db.

    Key point to this problem is controllers return type, if you want the real benefit of using odata you must return an IQueryable object and let the odata do the rest for you...

    0 comments No comments