Matt
Matt

Reputation: 26971

ODATA v4 batching - How can I process the request as a batch on the server?

With ODATA v4 batching - How can I process a batch request as a batch on the server?

I have a client successfully creating a POST request of 1000 creates as a batch to my webapi endpoint. My endpoint is running C# and Entity Framework.

The problem is that the controller in my endpoint processes each entry individually and makes a DB trip per create inside the batch request.

So while it is one POST, once on the server, they are not handled as a batch.

Is there a way to handle the batch request as a batch?

Upvotes: 0

Views: 2910

Answers (1)

TomDoesCode
TomDoesCode

Reputation: 3681

I added a SaveChanges call to me batch handler class in the ExecuteRequestMessagesAsync method and then only executed the SaveChanges in the controller if the request isn't a batch request. This means that although you execute each of your requests individually, you are only saving them to the database in one go.

In the controller, you can check whether this is part of a batch by checking the BatchId property. There is an extension method (GetODataBatchId) in System.Web.OData.Batch .ODataBatchHttpRequestMessageExtensions to get this but under the hood, this is just getting a property called BatchId from the HttpRequestMessage Properties collection. (source code: https://github.com/OData/WebApi/blob/master/src/System.Web.OData/OData/Batch/ODataBatchHttpRequestMessageExtensions.cs)

If you are interested in being "true to the spec" then you should save once per changeset rather than once for the whole request.

A good guide for this is available here: https://damienbod.com/2014/08/14/web-api-odata-v4-batching-part-10/

Upvotes: 1

Related Questions