Search code examples
c#odataodata-v4simple.odata

Creating an object and a relationship to that object in one batch using Simple.OData.Client


I want to create an object and a relationship in one batch using the Simple.OData.Client but I am struggling to see how I can do this. Without using batching, I can do this:

var client = new ODataClient("https://localhost/api/");
var parent = client.FindEntriesAsync("Parents").Result.First();
var child = await client.InsertEntryAsync("Children", new Dictionary<string, object> { { "Name", "ChildName" } });
await client.LinkEntryAsync("Parents", parent, "Children", child);

But when I try to put this into a batch, I can no longer use the return of the first call to create the child because it hasn't been made yet. I have tried using the same data that I use to create the object but this doesn't work, it just gives a null key in the create rel method on the server:

var client = new ODataClient("https://localhost/api/");
var batch = new ODataBatch(client);
var parent = client.FindEntriesAsync("Parents").Result.First();

batch += delegate (IODataClient c) { return c.InsertEntryAsync("Children", new Dictionary<string, object> { { "Name", "ChildName" } }); };
batch += delegate (IODataClient c) { return c.LinkEntryAsync("Parents", parent, "Children", new Dictionary<string, object> { { "Name", "ChildName" } }); };

await batch.ExecuteAsync();

I need to do this in a batch because my database requires that the relationship is set when I insert the data so it needs to be done in one database transaction.

Is this possible in Simple.OData.Client? If not, is it possible in OData generally?


Solution

  • Batching isn't required for doing this, you can create the relationship by including it like a property:

    var client = new ODataClient("https://localhost/api/");
    var parent = client.FindEntriesAsync("Parents").Result.First();
    var child = await client.InsertEntryAsync("Children", new Dictionary<string, object> { { "Name", "ChildName" }, { "Parent", parent } });
    

    That way it will still be processed in one database transaction.