0

I am working on the back end of a REST API -
For a POST request (in one of the scenarios) I need to validate if the object sent by the user is the same as the one stored in the Db.

What is an efficient way of comparing two objects in C#?

PS - I want the comparison logic to withstand the test of time, i.e. being a huge team I do not rely on people adding new fields in the IComparable logic. Anyone can add a new property to the object and that would skip the validation test if they do not add that to the comparison logic.

I am thinking of Deserializing the object stored in our database and compare it to the deserialized version of that the user POSTS.

Any thoughts?

divyanshm
  • 6,600
  • 7
  • 43
  • 72
  • 1
    Does the object have any properties which uniquely identify each instance? Something like a primary key in a database? Or are there any properties which must be unique? – John Saunders May 23 '15 at 06:02
  • Yes, there are. How does that help? – divyanshm May 23 '15 at 06:52
  • It helps because you only need to compare the properties which are part of the primary key in order to determine uniqueness. – John Saunders May 23 '15 at 06:53
  • Aah well, I didn't explain myself clearly then. Let us say for one scenario, i want to make a validation that throws if you try to update any property in the object. Since this is a POST call, I do not want to call into the update sproc if any property has been modified while my object happens to be in a terminal state. So, it's not just the primary key. – divyanshm May 23 '15 at 06:55
  • From the API perspective, I want to let the user know that he cannot modify a sub resource as it is in a terminal state. – divyanshm May 23 '15 at 06:56

1 Answers1

0

Automagically implement IComparable<T> on T for ValueObjects (objects for which their identity is all of their fields) is a form of Aspect-Oriented Programming (AOP).

There are various Aspect frameworks for C#.

In this case I would advise you use PM> Install-Package Equals.Fody.

To use it is pretty easy.

[Equals]
public class Foo
{
    public int X { get; set; }
    public int Y { get; set; }        
}
Community
  • 1
  • 1
Aron
  • 15,464
  • 3
  • 31
  • 64