nforss
nforss

Reputation: 1258

POSTing an entity type with children to an (MVC Web Api) OData service

I've been looking around for an answer to the following questions, but have so far not found one.

  1. Does the OData standard support doing a POST request containing an entity object with child entity objects?
  2. If so, does the ASP.NET MVC Web Api OData framework (EntitySetController) support this out of the box?

The scenario I have in mind goes something like the following. You have a Parent object, containing several Child objects. Could you then do a POST with a body like this?

{ "Property1" : "Property value", "Property2" : 100 
     "Children" : [
          { "ChildProperty" : "Some value" },
          { "ChildProperty" : "Some other value" },
          { "ChildProperty" : "Some third value" }
     ]
}

Also, if I later would like to add another child to the Parent object through POSTing a single child, is there a standardized way of linking them together? Something like

 { "ChildProperty" : "Fourth child property val", "Parent" : 321 }

where '321' is the ID of the parent object?

Many thanks for any pointers!

Upvotes: 6

Views: 5765

Answers (1)

RaghuRam Nadiminti
RaghuRam Nadiminti

Reputation: 6793

Yes, OData supports this and web API OData supports it as well. OData calls it deep insert. Here is the link to the spec.

Now there can be two types of deep inserts,

1) The nested item is new as well and should be created. An example of the json payload looks like this,

{
    ‘Property1’: 42,
    ‘Property2’: ‘Contoso’,
    ‘Children’: [
    {
        ‘ChildProperty’: 1,
        ……….
    },
    {
        ‘ChildProperty’: 2,
        ……….
    }]
}

2) The nested items already exist, the parent item is new and must be linked to the nested items. OData protocol calls this bind. Sample payload looks like,

{
    ‘Property1’: 42,
    ‘Property2’: ‘Contoso’,
    ‘[email protected]’: [
        “http://localhost/Children(1)”,
        “http://localhost/Children(2)”,
    ]
}

Web API OData supports first kind of deep inserts and doesn't have support for binds (the second example). In case of the first payload, your controller would receive a Parent object with the Children collection properly populated.

And regarding your second question, you have two options,

1) POST the child to ~/Parents(321)/Children URL

2) POST the child to ~/Children and then POST the ID link of this child from this response to the URL ~/Parents(321)/$links/Children.

You could refer to this link for this part of the OData spec.

Upvotes: 8

Related Questions