Search code examples
c#asp.net-web-apientity-framework-6odatapatch

OData Patch is not updating the database


I have a WebApi 2 controller. I want to use OData Patch on one of the controllers. Here's what I did so far.

I added the following line in WebApiConfig

config.MapODataServiceRoute("odata", "odata", GenerateEdmModle());
private static Microsoft.OData.Edm.IEdmModel GenerateEdmModle()
{
    var builder = new ODataConventionModelBuilder();
    builder.EntitySet<Auth>("Auths");
        
    return builder.GetEdmModel();
}

Then in the controller, This is how I'm trying to use patch method

[HttpPatch]
public async Task<IHttpActionResult> PatchAuth(int id, Delta<Auth> value)
{
    var auth = await db.Auth.FindAsync(id);
    if (auth == null) return NotFound();

    System.Diagnostics.Debug.WriteLine(auth.direction, auth.id);
    System.Diagnostics.Debug.WriteLine("Patching");
        
    try
    {
        value.Patch(auth);
        await db.SaveChangesAsync();
    }
    catch (Exception e)
    {
        System.Diagnostics.Debug.WriteLine(e.Message);
        return InternalServerError(e);
    }
    return Ok(value);
}

And here's how I'm sending it from angular service

// patch auth
service.patchAuth = function (authId, auth) {

    var request = $http({
        method: 'PATCH',
        url: baseUrl + 'api/Auths',
        data: JSON.stringify(auth),
        params: { id: authId },
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    });

    return (request.then(handleSuccess, handleError));
}

Here's what I see in Fiddler enter image description here

I see that the controller finds the Patch Method, and seems like it's trying to update, but the value never gets update.

I also add a breakpoint at value.Patch(auth) and checked the changedProperties, but there's nothing. I've been trying to find out what's causing this but haven't got a clue.


Solution

  • You specified application/x-www-form-urlencoded as your content type. Instead you have to use application/json.

    When you specify application/x-www-form-urlencoded the call is still routed to the correct patch handler (as in your case), however no changed properties are passed into Delta<T> by Web.Api.

    When you examine the raw HTTP Request in Fiddler your call should more look like this:

    PATCH http://www.example.com/api/Auths(5) HTTP/1.1
    Content-Type: application/json
    Host: www.example.com
    Content-Length: 20
    
    { "id" : 123456789 }