Created
April 25, 2018 14:16
-
-
Save ChadRoberts21/f4dd26776578199db3ee114e6713d717 to your computer and use it in GitHub Desktop.
A generic RESTful update method using reflection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
needs refining more to make it 100% bullet proof and REST compliant