Alonso Quesada
Alonso Quesada

Reputation: 125

Returning Nested Objects on .NET API using OData

I am working on a .NET API that uses OData and I am currently having issues returning nested objects back to the client.

Everything seems to be working, even if I put a break point on the Controller just before the response. I can see the Vendor object that is going to be returned with all the info has populated correctly, but when I look at the JSON response the Client received it only has primitive types and enums, every other property that is another object does not get serialized to the JSON result.

public class Vendor : IEntity
{
    public virtual int Id { get; set; }
    public virtual VendorAddress PrimaryAddress { get; set; }
    public virtual string VendorName { get; set; }
}

public class VendorAddress : IEntity
{
    public virtual int Id { get; set; }
    public virtual Vendor Vendor { get; set; }
    public virtual Address Address { get; set; }

}

 public class Address : IEntity
{
    public virtual int Id { get; set; }   
    public virtual string Line1 { get; set; }
    public virtual string Line2 { get; set; }     
    public virtual string Country { get; set; }
    public virtual string CountryCode { get; set; }
    public virtual string City { get; set; }
    public virtual string County { get; set; }
    public virtual string StateProvince { get; set; }
    public virtual string ZipCode { get; set; }    
}   

 public SingleResult<Vendor> Get([FromODataUri] int key)
{
    var result = _repository.Query<Vendor>().Where(a => a.Id == key);
    return SingleResult.Create(result);
}

Basically I want to return the Vendor info including the PrimaryAddress/Address information on the JSON result but can't seem to figure out how to.

Upvotes: 3

Views: 3354

Answers (1)

jps
jps

Reputation: 22495

VendorAddress and Address are so called Navigation Properties. You can get them by using $expand on your query. First add a [EnableQuery] to your Get method

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

then try a request in the form

<serviceUri>/Vendor(1)?$expand=VendorAddress
<serviceUri>/Vendor(1)?$expand=VendorAddress($expand=Address)

you'll have to add the line

config.Expand()

in your

WebApiConfig.Register(HTTPConfiguration config)

method.

Here is a example request on a test service:

http://services.odata.org/TripPinRESTierService/People('russellwhyte')?$expand=BestFriend($expand=Trips)

and some more information for reference: http://www.odata.org/odata-services/

Hope this helps.

Upvotes: 2

Related Questions