0

Assuming I wan't to use single class to create and update an object in REST API - how I can do this without code duplication?

Create an object (POST) - all fields should be [Required].

Update an object (PATCH) - I want to use same class but fields should not be required as it can be done partially.

I can use below class for POST but can't for PATCH - as only Name may be updated (provided along the request) - which is OK.

public class Person
{
  [Required]
  public string Name { get; set; }

  [Required]
  public string LastName { get; set; }
}

The only solution I see (that causes code duplication) is:

public class CreatePerson
{
  [Required]
  public string Name { get; set; }

  [Required]
  public string LastName { get; set; }
}
public class UpdatePerson
{
  public string Name { get; set; }

  public string LastName { get; set; }
}
  • https://stackoverflow.com/questions/26354853/conditionally-required-property-using-data-annotations – Pankaj Jun 10 '22 at 10:13
  • No, this is about fields dependency - not relevant here. – user18154574 Jun 10 '22 at 10:15
  • whit 2 classes in this case it isn't code duplication, this is the right way – spzvtbg Jun 10 '22 at 10:24
  • This is simplification - what if in the class there are another nested types with 50 fields in total? I need to duplicate all the content of the class just to remove data annotations. Then in case I need to update/edit any property I need to remember to do it in two classes. – user18154574 Jun 10 '22 at 10:29
  • Why don't you create a dto without annotations? In case of update use it as it is. In case of create use reflection to check that all properties value are different than default. – Peter Csala Jun 10 '22 at 21:26
  • Btw why do you use PATCH for update? Why don't you use PUT? – Peter Csala Jun 10 '22 at 21:27
  • PATCH is for partial updates and this is a requirement - I don't want to pass whole object but i.e. add new address item (assuming above example has another Address type filed with another properties. – user18154574 Jun 12 '22 at 19:56

0 Answers0