To update an entity in ASP.NET Web API, PUT request is used and we have to send all the properties even if only a subset have changed means if only one field is updated on the client side, we have to send the entire model back to the server to make an update. It’s not a cool way. PATCH request allows you to send just the modified properties for partial model updates. It reduces complexity in case of bigger tables. Here is a usage example to implement HTTP Patch request in ASP.NET Web API to update data with EF DB First.

Table Structure:

Let us consider following table structure:
DB Structure HTTP PATCH Requests (Partial Updates) in ASP.NET Web API and EF DB First

In our ASP.NET Web API app, Right Click on Models folder > Add > New Item > Select “ADO.NET Entity Data Model” > Enter Name and click “Add”
Select “Generate From Database” > Next
Select Database Connection (New Connection if doesn’t exist), Make sure “Save entity connection setting in web.config as” option true and Enter Name > Next
Select the table > Enter ModelNamespace > Finish.

Web API:

		[AcceptVerbs("PATCH")]
        public HttpResponseMessage PatchDoc(int id, Delta<DocInfo> newDoc)
        {
            using (DBDocEntities objContext = new DBDocEntities()){
            DocInfo doc = objContext.DocInfoes.SingleOrDefault(p => p.DocID  == id);
            if (doc == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            newDoc.Patch(doc);
            objContext.SaveChanges();                
            }
            return Request.CreateResponse(HttpStatusCode.NoContent);
        }

In above method, we are using Delta<DocInfo> type argument instead of DocInfo. Delta<DocInfo> allows to set any DocInfo property and also track which properties are set. Delta class provides Patch method which copies the properties that have been set.

Note: oData 0.2.0 alpha is used. It may be subject to change. You can get new nuget package for building OData.

Client Side:

We are going to update only Revision property for a particular document. For simplicity, we are taking same app to consume web API and using following ajax method in the view.

    var obj = { Revision : "2"};

    $.ajax({
        url: 'api/values/1',
        type: 'PATCH',
        data: JSON.stringify(obj),
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) {            
        }
    });

It will update Revision to 2 for DocID = 1.

delta patch request HTTP PATCH Requests (Partial Updates) in ASP.NET Web API and EF DB First

Hope, It helps.

Comments:  1

  • Yousof

    I can check the fields against Null, if they r null I forget about them. Right? what s the point of using Patch then?