Wednesday, January 14, 2015

WebAPI OData: Only entity types support $select and $expand

I used to get this because I was trying to return a complex type which was not an entity type and use "expand" on it so to get a child property:

builder.EntitySet<MyComplexType>("MyComplexTypes").EntityType.Collection.Action("MyAction").Returns<MyComplexType>()
[HttpPost, EnableQuery(AllowedQueryOptions = AllowedQueryOptions.Expand)]
public IHttpActionResult MyAction(ODataActionParameters parameters)
{
 return Ok(new MyComplexType());
}

http://host/api/Entities/Default.MyAction?$expand=ChildProperty

Accessing this URL triggers:

"Only entity types support $select and $expand"

Instead of converting the type, which would have made non sens in my situation, here's what I did:

builder.EntitySet<MyComplexType>("MyComplexTypes").EntityType.Collection.Action("MyAction").Returns<string>()
[HttpPost]
public IHttpActionResult MyAction(ODataActionParameters parameters)
{
 return Json(new MyComplexType());
}

http://host/api/Entities/Default.MyAction

This returns a new MyComplexType object with all its children properties serialized.