Home > Software engineering >  Is there an approach in C# WebAPI with DTO's to only update elements that need to change?
Is there an approach in C# WebAPI with DTO's to only update elements that need to change?

Time:09-19

In the tutorials I've walked through around creating an API in C#, I've gone through creating an HTTP PUT command for updating records in a table contained in a database.

The examples I've seen, essentially, I create a DTO around the fields that can be updated in that table. For example, I have a class that looks like the following:

public class UpdateTablenameDTO
{
public int ID { get; set; }

public int IsActive { get; set; }

public int IsDeleted { get; set;}

...

I then built a controller and all of the fields in my UpdateTablenameDTO appear as elements expected when I do an update.

What I wanted to know is there a proper approach to not requiring all of the elements in the Update DTO when doing the Update call? When I send my payload to include only ID and IsActive, it complained that it needed the rest of my fields. When I think this through, there could be a situation that a user is sitting on a screen with an old state but with a specific update that they want to send through (i.e. make the record inactive).

I don't necessarily want to update all of the elements, really only the specific changes, which would be the only thing I would want to send, along with the ID for identification. I suppose the way I could do this is to check if the record has changed since the user last viewed it upon updating, but I wanted to make sure I wasn't missing something obvious for this kind of scenario.

CodePudding user response:

You can use Nullable value types to indicate that a property is "optional". The deserializer on the webapi side will keep the property as null when no value is provided. You can define the receiving DTO as follow:

public class UpdateTablenameDTO
{
    public int ID { get; set; } // still required

    public int? IsActive { get; set; } // now it's optional

    public int? IsDeleted { get; set;} // optional as well
}

When you provide the JSON body as {"ID":5, "IsActive": 20} then you get an UpdateTablenameDTO instance as follow:

new UpdateTablenameDTO {
    ID = 5,
    IsActive = 20,
    // IsDeleted = null
}

When you receive such an object, you can simply do a check against null or check the HasValue property to see, if there was a value in the request.

if (data.IsActive.HasValue) {
    // do something with "data.IsActive.Value"
}
  • Related