Generic Code to compare the properties of objects of same type

Deysomnath
Posted by Deysomnath under C# category on | Points: 40 | Views : 299
This article is based on a generic code to compare the properties of objects of the same Type .
Many times we come across a requirement to compare the modified values with the original values to check whether there are any changes, if changes are there save the data in to the database.

Ex. If user update any row of the grid and click SAVE button. Application need to make sure user has really change any value of the row before saving it to database. Here is a generic code example to do the same.

Create a model which will be used to bind the grid in UI.

Public class MasterEmp<T> where : new()
{
private T Entity { get; set; }
public T OriginalEntity { get; set; }
}

Public class Employee
{
Public int EmpID { get; set; }
Public string EmpName{ get; set; }
Public string salary{ get; set; }
Public string Dept{ get; set; }
}



Create Controller Class

Public class EmpController 
{
[HttpPost]
public JsonResult UpdateEmployee( IEnumerable< MasterEmp< Employee>> models)
{
var returnData = new DataModel< MasterEmp < Employee >>();

if((models != null) && (ModelState.IsValid))
{


If(IsPropertiesChanged(models.OriginalEntity , models.Entity)
{
// Call database to Save the data.
}

}

return new JsonResult
{
Data = result,
JsonRequestBehavior = JsonRequestBehavior.AllowGet

};

}

Private bool IsPropertiesChanged<T>(T orginal ,T modified) where T : class
{
if(orginal != null && modified != null)
{
Type sourceType = typeof(T);

foreach (System.Reflection.PropertyInfo pi in sourceType.GetProperties( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
object orginalValue = sourceType.GetProperty(pi.Name).GetValue(orginal, null);
object modifiedValue = sourceType.GetProperty(pi.Name).GetValue(modified, null);
if ((orginalValue == null) || !orginalValue.Equals(modifiedValue))
{
return true;
}
}
return false;
}
return orginalValue == modifiedValue;
}

}


The above code is a generic code can work for any properties. You can use below code also in place of this method "IsPropertiesChanged(...)" but you have to repeat this every time for different properties.

If(models.OriginalEntity.Dept!= models.Entity.Dept
|| models.OriginalEntity. EmpName!= models.Entity. EmpName
|| models.OriginalEntity.salary!= models.Entity.salary)
{
// Call database to Save the data.
}

Comments or Responses

Login to post response