This is a series of blogs detailing my introduction to using OData v4 with C# and ASP.NET WebApi.
The source code for the project can be found here.
Up to now we have been creating individual controller actions for our entities either for selecting all entities or selecting entities by key. One of the powers of OData is the query like syntax we can apply within the Url which does not need additional controller actions. In this blog we will look at the EXPAND query option.
Creating the Project
The Project is called Part14.
Query All Employees
From Postman issue a GET request with http://localhost:40000/OData/Employees.
Notice when we return all the Employees it makes no reference to a property called orders. Let’s check the metadata.
Notice we have a NavigationProperty called Orders. In our Employee class we have a property defined as follows:
public virtual ICollection<Order> Orders { get; set; }
The EDM builder recognised we had an Orders collection and configured it for us. There is a One to Many relationship between Customers and Orders
Get the Orders for Employee ID 1
From Postman issue a GET request with http://localhost:40000/odata/Employees(1)?$expand=Orders.
All the properties for Employee and Order are returned. Let reduce the number to LastName and FirstName only.
From Postman issue a GET request with http://localhost:40000/odata/Employees(1)?$select=LastName,FirstName&$expand=Orders.
That looks better. Let’s display the OrderID only.
From Postman issue a GET request with http://localhost:40000/odata/Employees(1)?$select=LastName,FirstName&$expand=Orders($select=OrderID).
We get an error. In order to play with properties on the Order entity we need to define an entity set in the WebApiConfig.cs
private static IEdmModel GetEdmModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Employee>("Employees")
.EntityType
.Select()
.Filter()
.Filter(QueryOptionSetting.Disabled, "City")
.Expand()
.Select(SelectExpandType.Disabled, "Notes");
builder.EntityType<Employee>().Ignore(p => p.Photo);
builder.EntityType<Employee>().Ignore(p => p.PhotoPath);
builder.EntitySet<Order>("Orders")
.EntityType
.Select();
return builder.GetEdmModel();
}
Reissue the query.
This is all we will discuss about $expand for this blog. In the next blog I’ll take a look at the $count query option.