"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Using $select, $expand, and $value in ASP.NET Web API 2 OData

by Mike Wasson

Web API 2 adds support for the $expand, $select, and $value options in OData. These options allow a client to control the representation that it gets back from the server.

Example Schema

For this article, I’ll use an OData service that defines three entities: Product, Supplier, and Category. Each product has one category and one supplier.

Here are the C# classes that define the entity models:

[!code-csharpMain]

   1:  public class Supplier
   2:  {
   3:      [Key]
   4:      public string Key {get; set; }
   5:      public string Name { get; set; }
   6:  }
   7:  public class Category
   8:  {
   9:      public int ID { get; set; }
  10:      public string Name { get; set; }
  11:      public virtual ICollection<Product> Products { get; set; }
  12:  }
  13:   
  14:  public class Product
  15:  {
  16:      public int ID { get; set; }
  17:      public string Name { get; set; }
  18:      public decimal Price { get; set; }
  19:   
  20:      [ForeignKey("Category")]
  21:      public int CategoryId { get; set; }
  22:      public Category Category { get; set; }
  23:   
  24:      [ForeignKey("Supplier")]
  25:      public string SupplierId { get; set; }
  26:      public virtual Supplier Supplier { get; set; }
  27:  }

Notice that the Product class defines navigation properties for the Supplier and Category. The Category class defines a navigation property for the products in each category.

To create an OData endpoint for this schema, use the Visual Studio 2013 scaffolding, as described in Creating an OData Endpoint in ASP.NET Web API. Add separate controllers for Product, Category, and Supplier.

Enabling $expand and $select

In Visual Studio 2013, the Web API OData scaffolding creates a controller that automatically supports $expand and $select. For reference, here are the requirements to support $expand and $select in a controller.

For collections, the controller’s Get method must return an IQueryable.

[!code-csharpMain]

   1:  [Queryable]
   2:  public IQueryable<Category> GetCategories()
   3:  {
   4:      return db.Categories;
   5:  }

For single entities, return a SingleResult<T>, where T is an IQueryable that contains zero or one entities.

[!code-csharpMain]

   1:  [Queryable]
   2:  public SingleResult<Category> GetCategory([FromODataUri] int key)
   3:  {
   4:      return SingleResult.Create(db.Categories.Where(c => c.ID == key));
   5:  }

Also, decorate your Get methods with the [Queryable] attribute, as shown in the previous code snippets. Alternatively, call EnableQuerySupport on the HttpConfiguration object at startup. (For more information, see Enabling OData Query Options.)

Using $expand

When you query an OData entity or collection, the default response does not include related entities. For example, here is the default response for the Categories entity set:

[!code-consoleMain]

   1:  {
   2:    "odata.metadata":"http://localhost/odata/$metadata#Categories",
   3:    "value":[
   4:      {"ID":1,"Name":"Apparel"},
   5:      {"ID":2,"Name":"Toys"}
   6:    ]
   7:  }

As you can see, the response does not include any products, even though the Category entity has a Products navigation link. However, the client can use $expand to get the list of products for each category. The $expand option goes in the query string of the request:

[!code-consoleMain]

   1:  GET http://localhost/odata/Categories?$expand=Products

Now the server will include the products for each category, inline with the categories. Here is the response payload:

[!code-consoleMain]

   1:  {
   2:    "odata.metadata":"http://localhost/odata/$metadata#Categories",
   3:    "value":[
   4:      {
   5:        "Products":[
   6:          {"ID":1,"Name":"Hat","Price":"15.00","CategoryId":1,"SupplierId":"CTSO"},
   7:          {"ID":2,"Name":"Scarf","Price":"12.00","CategoryId":1,"SupplierId":"CTSO"},
   8:          {"ID":3,"Name":"Socks","Price":"5.00","CategoryId":1,"SupplierId":"FBRK"}
   9:        ],
  10:        "ID":1,
  11:        "Name":"Apparel"
  12:      },
  13:      {
  14:        "Products":[
  15:          {"ID":4,"Name":"Yo-yo","Price":"4.95","CategoryId":2,"SupplierId":"WING"},
  16:          {"ID":5,"Name":"Puzzle","Price":"8.00","CategoryId":2,"SupplierId":"WING"}
  17:        ],
  18:        "ID":2,
  19:        "Name":"Toys"
  20:      }
  21:    ]
  22:  }

Notice that each entry in the “value” array contains a Products list.

The $expand option takes a comma-separated list of navigation properties to expand. The following request expands both the category and the supplier for a product.

[!code-consoleMain]

   1:  GET http://localhost/odata/Products(1)?$expand=Category,Supplier

Here is the response body:

[!code-consoleMain]

   1:  {
   2:    "odata.metadata":"http://localhost/odata/$metadata#Products/@Element",
   3:    "Category": {"ID":1,"Name":"Apparel"},
   4:    "Supplier":{"Key":"CTSO","Name":"Contoso, Ltd."},
   5:    "ID":1,
   6:    "Name":"Hat",
   7:    "Price":"15.00",
   8:    "CategoryId":1,
   9:    "SupplierId":"CTSO"
  10:  }

You can expand more than one level of navigation property. The following example includes all the products for a category and also the supplier for each product.

[!code-consoleMain]

   1:  GET http://localhost/odata/Categories(1)?$expand=Products/Supplier

Here is the response body:

[!code-consoleMain]

   1:  {
   2:    "odata.metadata":"http://localhost/odata/$metadata#Categories/@Element",
   3:    "Products":[
   4:      {
   5:        "Supplier":{"Key":"CTSO","Name":"Contoso, Ltd."},
   6:        "ID":1,"Name":"Hat","Price":"15.00","CategoryId":1,"SupplierId":"CTSO"
   7:      },
   8:      {
   9:        "Supplier":{"Key":"CTSO","Name":"Contoso, Ltd."},
  10:        "ID":2,"Name":"Scarf","Price":"12.00","CategoryId":1,"SupplierId":"CTSO"
  11:      },{
  12:        "Supplier":{
  13:          "Key":"FBRK","Name":"Fabrikam, Inc."
  14:        },"ID":3,"Name":"Socks","Price":"5.00","CategoryId":1,"SupplierId":"FBRK"
  15:      }
  16:    ],"ID":1,"Name":"Apparel"
  17:  }

By default, Web API limits the maximum expansion depth to 2. That prevents the client from sending complex requests like $expand=Orders/OrderDetails/Product/Supplier/Region, which might be inefficient to query and create large responses. To override the default, set the MaxExpansionDepth property on the [Queryable] attribute.

[!code-csharpMain]

   1:  [Queryable(MaxExpansionDepth=4)]
   2:  public IQueryable<Category> GetCategories()
   3:  {
   4:      return db.Categories;
   5:  }

For more information about the expandoption, see[ExpandSystemQueryOption(expand)](http://www.odata.org/documentation/odata-v2-documentation/uri-conventions/#46_Expand_System_Query_Option_expand) in the official OData documentation.

Using $select

The $select option specifies a subset of properties to include in the response body. For example, to get only the name and price of each product, use the following query:

[!code-consoleMain]

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

Here is the response body:

[!code-consoleMain]

   1:  {
   2:    "odata.metadata":"http://localhost/odata/$metadata#Products&$select=Price,Name",
   3:    "value":[
   4:      {"Price":"15.00","Name":"Hat"},
   5:      {"Price":"12.00","Name":"Scarf"},
   6:      {"Price":"5.00","Name":"Socks"},
   7:      {"Price":"4.95","Name":"Yo-yo"},
   8:      {"Price":"8.00","Name":"Puzzle"}
   9:    ]
  10:  }

You can combine $select and $expand in the same query. Make sure to include the expanded property in the $select option. For example, the following request gets the product name and supplier.

[!code-consoleMain]

   1:  GET http://localhost/odata/Products?$select=Name,Supplier&$expand=Supplier

Here is the response body:

[!code-consoleMain]

   1:  {
   2:    "odata.metadata":"http://localhost/odata/$metadata#Products&$select=Name,Supplier",
   3:    "value":[
   4:      {
   5:        "Supplier":{"Key":"CTSO","Name":"Contoso, Ltd."},
   6:        "Name":"Hat"
   7:      },
   8:      {
   9:        "Supplier":{"Key":"CTSO","Name":"Contoso, Ltd."},
  10:        "Name":"Scarf"
  11:      },
  12:      {
  13:        "Supplier":{"Key":"FBRK","Name":"Fabrikam, Inc."},
  14:        "Name":"Socks"
  15:      },
  16:      {
  17:        "Supplier":{"Key":"WING","Name":"Wingtip Toys"},
  18:        "Name":"Yo-yo"
  19:      },
  20:      {
  21:        "Supplier":{"Key":"WING","Name":"Wingtip Toys"},
  22:        "Name":"Puzzle"
  23:     }
  24:    ]
  25:  }

You can also select the properties within an expanded property. The following request expands Products and selects category name plus product name.

[!code-consoleMain]

   1:  GET http://localhost/odata/Categories?$expand=Products&$select=Name,Products/Name

Here is the response body:

[!code-consoleMain]

   1:  {
   2:    "odata.metadata":"http://localhost/odata/$metadata#Categories&$select=Name,Products/Name",
   3:    "value":[ 
   4:      {
   5:        "Products":[ {"Name":"Hat"},{"Name":"Scarf"},{"Name":"Socks"} ],
   6:        "Name":"Apparel"
   7:      },
   8:      {
   9:        "Products":[ {"Name":"Yo-yo"},{"Name":"Puzzle"} ],
  10:        "Name":"Toys"
  11:      }
  12:    ]
  13:  }

For more information about the selectoption, see[SelectSystemQueryOption(select)](http://www.odata.org/documentation/odata-v2-documentation/uri-conventions/#48_Select_System_Query_Option_select) in the official OData documentation.

Getting Individual Properties of an Entity ($value)

There are two ways for an OData client to get an individual property from an entity. The client can either get the value in OData format, or get the raw value of the property.

The following request gets a property in OData format.

[!code-consoleMain]

   1:  GET http://localhost/odata/Products(1)/Name

Here is an example response in JSON format:

[!code-consoleMain]

   1:  HTTP/1.1 200 OK
   2:  Content-Type: application/json; odata=minimalmetadata; streaming=true; charset=utf-8
   3:  DataServiceVersion: 3.0
   4:  Content-Length: 90
   5:   
   6:  {
   7:    "odata.metadata":"http://localhost:14239/odata/$metadata#Edm.String",
   8:    "value":"Hat"
   9:  }

To get the raw value of the property, append $value to the URI:

[!code-consoleMain]

   1:  GET http://localhost/odata/Products(1)/Name/$value

Here is the response. Notice that the content type is “text/plain”, not JSON.

[!code-consoleMain]

   1:  HTTP/1.1 200 OK
   2:  Content-Type: text/plain; charset=utf-8
   3:  DataServiceVersion: 3.0
   4:  Content-Length: 3
   5:   
   6:  Hat

To support these queries in your OData controller, add a method named GetProperty, where Property is the name of the property. For example, the method to get the Name property would be named GetName. The method should return the value of that property:

[!code-csharpMain]

   1:  public async Task<IHttpActionResult> GetName(int key)
   2:  {
   3:      Product product = await db.Products.FindAsync(key);
   4:      if (product == null)
   5:      {
   6:          return NotFound();
   7:      }
   8:      return Ok(product.Name);
   9:  }



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-api/overview/odata-support-in-aspnet-web-api/using-select-expand-and-value.htm
< THANKS ME>