Expanding results with linked entries

object edited this page Oct 9, 2012 · 10 revisions

Using Simple.Data With 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 category = _db.Category
    .WithProducts()
    .FindByCategoryName("Beverages");
Assert.Equal("Beverages", category.CategoryName);
Assert.True(category.Products.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 = _db.Category
    .All()
    .WithProducts()
    .ToList();
Assert.True(categories.Count > 0);
Assert.True(categories[0].Products.Count > 0);

Request URI: GET Categories?expand=Products


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

var products = _db.Products
    .All()
    .WithCategory()
    .ToList();
Assert.True(products.Count > 0);
Assert.Equal("Beverages", products[0].Category.CategoryName);

Request URI: GET Products?$expand=Category


Get a customer by key, expand with associated orders

var customer = _db.Customer
    .WithOrders()
    .Get("ALFKI");
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 = _db.Employees
    .All()
    .WithSubordinates()
    .ToList();
Assert.True(employees.Count > 0);
Assert.True(employees[0].Subordinates.Count == 0);
Assert.True(employees[1].Subordinates.Count > 0);

Request URI: GET Employees?$expand=Subordinates


Find an employee with it's superior

var employee = _db.Employees
    .WithSuperior()
    .FindByFirstNameAndLastName("Nancy", "Davolio");
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