1
votes

Consider the following domain model:

public class Employee 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int AddressId { get; set; }
    public Address Address { get; set; }
    public ICollection<Message> Messages { get; set; }
}

public class Address
{
    public int Id { get; set; }
    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    .....
}

public class Message
{
    public int Id { get; set; }
    public Message Message { get; set; }
}

We use EF6 code first to create the database for this model. The address data is saved to its own table. On top of EF6 we use ASP.NET Web API 2.0 and OData. The ODataConventionModelBuilder creates an EntitySet for Employee and a ComplexType for Address.

In order to return an Employee we created the following action:

[EnableQuery]
public SingleResult<Employee> Get([FromODataUri] int key)

In order to always return the Address we use an EF Include on the Address property. So when we use the following url:

/api/Employees(1)

The Employee with id 1 will be returned with its Address property filled.

However, when we use $expand to expand the Messages for the use we loose the Address data:

/api/Employee(1)?$expand=Messages

Returns an Employee object with Messages expanded, but without the Address data. The EnableQuery attribute applies the expand to our query-able but overwrites the EF Includes that we specified in the API. We cannot expand the Address too from the client because Complex types cannot be expanded in OData. When we change the Address Odata type to an Entity we need multiple calls to create or update an Employee. One call to an Address controler which handles create/update for addresses and one call to the Employee controller to handle create/update for employees.

So my question: Is it possible to preserve the Address include without specifying it from the client?

1

1 Answers

0
votes

We use element type like Employee when select all properties, so we lose your include Address when composing the Linq expression, but if you select Address, it will come in result because it's not select all, so a work around maybe request like: $expand=Messages&$select=Address,Id,Name

Relative code: https://github.com/OData/WebApi/blob/master/OData/src/System.Web.OData/OData/Query/Expressions/SelectExpandBinder.cs#L272-L292