Search code examples
databaseasp.net-web-apitransactionsodata

Transactions using ODataControllers


Typically, an ODataController is set up to handle CRUD and other actions for one underlying DB entity. This works well when you are updating one or more customer orders, for example.

However, how do you commit changes to two or more entities in one transaction - for example, update a customer order with several related customer order details? Can this (or should this) be done using one ODataController? Or, is it better to put a service component on top of the ODataControllers, which wraps the entire transaction?


Solution

  • The Batch feature is designed to handle multi-operations within one http request. The batch requests look like:

    POST /service/$batch HTTP/1.1 
    Host: host 
    OData-Version: 4.0
    Content-Type: multipart/mixed;boundary=batch_36522ad7-fc75-4b56-8c71-56071383e77b
    
    --batch_36522ad7-fc75-4b56-8c71-56071383e77b
    Content-Type: multipart/mixed;boundary=changeset_77162fcd-b8da-41ac-a9f8-9357efbbd
    
    --changeset_77162fcd-b8da-41ac-a9f8-9357efbbd
    Content-Type: application/http 
    Content-Transfer-Encoding: binary 
    Content-ID: 1 
    
    POST /service/Customers HTTP/1.1 
    Host: host  
    Content-Type: application/atom+xml;type=entry 
    Content-Length: ### 
    
    <AtomPub representation of a new Customer>
    --changeset_77162fcd-b8da-41ac-a9f8-9357efbbd
    Content-Type: application/http 
    Content-Transfer-Encoding: binary 
    Content-ID: 2
    
    POST $1/Orders HTTP/1.1 
    Host: host 
    Content-Type: application/atom+xml;type=entry 
    Content-Length: ### 
    
    <AtomPub representation of a new Order>
    --changeset_77162fcd-b8da-41ac-a9f8-9357efbbd--
    --batch_36522ad7-fc75-4b56-8c71-56071383e77b--
    

    Each ChangeSet must be treated as a transaction. Here is a sample for your reference:http://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v3/ODataEFBatchSample/.