Skip to content

Instantly share code, notes, and snippets.

@ChadRoberts21
Created April 25, 2018 14:16
Show Gist options
  • Save ChadRoberts21/f4dd26776578199db3ee114e6713d717 to your computer and use it in GitHub Desktop.
Save ChadRoberts21/f4dd26776578199db3ee114e6713d717 to your computer and use it in GitHub Desktop.
A generic RESTful update method using reflection
public static bool Update<T>(long id, T updatedObj)
{
using (DBContext db = new DbContext())
{
var originalObj = db.T.Where(x => x.id == id).FirstOrDefault();
var rawObj = new T();
if (originalObj != null)
{
foreach (PropertyInfo propertyInfo in updatedObj.GetType().GetProperties())
{
var upvalue = propertyInfo.GetValue(updatedObj);
var origvalue = propertyInfo.GetValue(originalObj);
var rawvalue = propertyInfo.GetValue(rawObj);
if (upvalue == null || Nullable.GetUnderlyingType(poivalue.GetType()) != null)
{
if ((upvalue!=null && origvalue!=null && rawvalue != null) && !upvalue.Equals(origvalue) && !upvalue.Equals(rawvalue))
{
propertyInfo.SetValue(originalObj, propertyInfo.GetValue(updatedObj));
}
}
else
{
if (!poivalue.Equals(origvalue))
{
propertyInfo.SetValue(originalObj, propertyInfo.GetValue(updatedObj));
}
}
}
db.SaveChanges();
return true;
}
return false;
}
}
@ChadRoberts21
Copy link
Author

needs refining more to make it 100% bullet proof and REST compliant

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment