I've been looking around for an answer to the following questions, but have so far not found one.
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!
For this tutorial, we'll use Entity Framework (EF) Code First to create the back-end database. Web API OData does not require EF. Use any data-access layer that can translate database entities into models.
Creating an OData service. To define an OData service, simply derive from ODataController. This is a base class for OData controllers that support writing and reading data using the OData formats.
OData uses the Entity Data Model (EDM) to describe the structure of data. In ASP.NET Core OData, it's easy to build the EDM based on the above CLR types (Entity, Complex, Enum). With that in mind, let's add the following private static method at the end of Startup.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With