6

I have a big model

public class SomeModel
{
        public int Id { get; set; }
        .....A lot(24) of Fields here.....
}

Now on Post ActionResult Edit(somemodel SomeModel) I want to check if anything has been changed by user with respect to original model values in database. Using If Else makes for a lot of messy code. Is there anyway to check if something was altered by the user and if possible what field was altered by user?

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
Flood Gravemind
  • 3,773
  • 12
  • 47
  • 79
  • 1
    I think you will have to extend the Equals Operator: Something like this: http://stackoverflow.com/a/4616717/1910735 – Dawood Awan Apr 01 '15 at 13:33
  • Also see http://stackoverflow.com/questions/506096/comparing-object-properties-in-c-sharp – Ondrej Svejdar Apr 01 '15 at 13:40
  • If this is an concurrency issue and you are using EF you can [check out this tutorial](http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application) . Even if it is not, they use an interesting technique with a byte[] timestamp that you could probably tweek to serve your specific needs for your application –  Apr 01 '15 at 16:32

1 Answers1

3

I was thinking about using a method like this one

    public class SomeModel
    {
    //... 
     public override bool Equals(object obj)
        {
      var type = this.GetType();
      bool SameObj = true;
     //for each public property from 'SomeModel'
     //[EDITED]type.GetProperties().Each(prop=>{ //  Sorry i'm using custom extension methode here
     //you should probably use this instead
     type.GetProperties().ToList().ForEach(prop=>{
                      //dynamically checks that they're equals 
                      if(!prop.GetValue(this,null).Equals(prop.GetValue(obj,null))){
                          SameObj=false;
                      }
                    }
                return SameObj;
    }
   }

/!\ Edited

Emmanuel M.
  • 441
  • 6
  • 11