Skip to content

Expanding results with linked entries

object edited this page Feb 12, 2013 · 23 revisions

Using Expand clause it's possible to expand results with associated data. Expanded entries must be defined as relationships in OData service schema.


Find a category by name, expand with associated products

var x = ODataFilter.Expression;
var category = client
    .For("Categories")
    .Filter(x.CategoryName == "Beverages")
    .Expand("Products")
    .FindEntry();
Assert.Equal("Beverages", category["CategoryName"]);
Assert.True((category.Products as IDictionary<string, object>).Count > 0);

Request URI: GET Categories?$filter=CategoryName+eq+%27Beverages%27&$expand=Products&$top=1


Find all categories expanded with associated products (one-to-many relationship expansion)

var categories = client
    .For("Categories")
    .Expand("Products")
    .FindEntries();
Assert.True(categories.Count > 0);
Assert.True((categories[0]["Products"] as IDictionary<string, object>).Count > 0);

Request URI: GET Categories?expand=Products


Find all products expanded with linked categories (many-to-one relationship expansion)

var products = client
    .For("Products")
    .Expand("Category")
    .FindEntries();
Assert.True(products.Count > 0);
Assert.Equal("Beverages", (products[0]["Category"] as IDictionary<string, object>).CategoryName);

Request URI: GET Products?$expand=Category


Get a customer by key, expand with associated orders

var customer = client
    .For("Customer")
    .Get("ALFKI")
    .Expand("Orders")
    .FindEntry();
Assert.Equal("ALFKI", customer["CustomerID"]);
Assert.True(customer.Orders.Count > 0);

Request URI: GET Customers(%27ALFKI%27)?$expand=Orders


Find all employees, expand with associated subordinates

var employees = client
    .For("Employees")
    .Expand("Subordinates")
    .FindEntries();
Assert.True(employees.Count > 0);
Assert.True((employees[0]["Subordinates"] as IDictionary<string, object>).Count == 0);
Assert.True((employees[0]["Subordinates"] as IDictionary<string, object>).Count > 0);

Request URI: GET Employees?$expand=Subordinates


Find an employee with it's superior

var x = ODataFilter.Expression;
var employee = client
    .For("Employees")
    .Filter(x.FirstName == "Nancy" && x.LastName == "Davolio")
    .Expand("Superior")
    .FindEntries();
Assert.NotNull(employee);
Assert.NotNull(employee["Superior"]);

Request URI: GET Employees?$filter=(FirstName+eq+%27Nancy%27+and+LastName+eq+%27Davolio%27)&$expand=Superior&$top=1


See also:
Retrieving linked entries without fetching its owners
Retrieving data

Clone this wiki locally