How to correctly create and link one-to-one relationships in a single POST request using OData

In the OData: Operations documentation, section 2.4, the fourth paragraph, it reads when creating an object with POST, it is also possible to create a link in the same request. However, I am having trouble trying to make this work. A similar question was asked about creating many-to-many links when creating, and it seems that this particular scenario is not possible without a batch request. Below is the script I'm trying to create using this OData read write service sample .

Create a new product called "Test Product" and bind it to category (0) in one POST using JSON.

I tried...

POST /OData/OData.svc/Products HTTP/1.1
Accept: application/json
Content-Type: application/json

{"ID": 99, "Name": "Test Product", "Description": "Simple Test", "ReleaseDate": "\ / Date (1210204800000) \ /", "DiscontinuedDate": null, "Rating": 3, "Price": "99.99", "Category": "http://services.odata.org/OData/OData.svc/Categories(0)"}

and...

POST /OData/OData.svc/Products HTTP/1.1
Accept: application/json
Content-Type: application/json

{"ID": 99, "Name": "Test Product", "Description": "Simple Test", "ReleaseDate": "\ / Date (1210204800000) \ /", "DiscontinuedDate": null, "Rating": 3, "Price": "99.99", "Category": {"uri": "http://services.odata.org/OData/OData.svc/Categories(0)"}}

Both are the result of failures.

Another example of using the atom format ...

<?xml version="1.0" encoding="utf-8"?>
<entry xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom">
    <title type="text"/>
    <updated>2010-02-27T21:36:47Z</updated>
    <author>
        <name/>
    </author>
    <Link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Category" type="application/atom+xml;type=Entry" title="Category" href="Categories(0)"/>
    <category term="ODataDemo.Product" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"/>
    <content type="application/xml">
        <m:properties>
            <d:ID m:type="Edm.Int32">99</d:ID>
            <d:Name m:type="Edm.String">New Product</d:Name>
            <d:ReleaseDate m:type="Edm.DateTime">1992-01-01T00:00:00</d:ReleaseDate>
            <d:DiscontinuedDate m:type="Edm.DateTime" m:null="true"/>
            <d:Rating m:type="Edm.Int32">4</d:Rating>
            <d:Price m:type="Edm.Decimal">2.5</d:Price>
        </m:properties>
    </content>
</entry>

201 , .

. .

+3
1

Microsoft . Atom "L", . IE.

<link rel="http://schemas.microsoft.com/ado/2007/08/dataservices/related/Category" type="application/atom+xml;type=entry" title="Category" href="Categories(0)"/>

JSON "__metadata", . IE.

{
 Prop1: ...,
 Prop2: ...,
 LinkProp1: { __metadata: { uri: "http://..." } }
}
+5

Source: https://habr.com/ru/post/1784476/


All Articles