I try to create some method that can update any changed data from changed Data object (this object is generated by ASP.NET MVC) to old Data object (this object is retrieved from current data in DBMS) like the following code.
public static bool UpdateSomeData(SomeEntities context, SomeModelType changedData)
{
var oldData = GetSomeModelTypeById(context, changedData.ID);
UpdateModel(oldData, changedData);
return context.SaveChanges() > 0;
}
I try to create method for saving any changed data without affects other unchanged data like the following source code.
public static void UpdateModel<TModel>(TModel oldData, TModel changedData)
{
foreach (var pi in typeof(TModel).GetProperties()
.Where
(
// Ignore Change ID property for security reason
x => x.Name.ToUpper() != "ID" &&
x.CanRead &&
x.CanWrite &&
(
// It must be primitive type or Guid
x.PropertyType.FullName.StartsWith("System") &&
!x.PropertyType.FullName.StartsWith("System.Collection") &&
!x.PropertyType.FullName.StartsWith("System.Data.Entity.DynamicProxies")
)
)
{
var oldValue = pi.GetValue(oldData, null);
var newValue = pi.GetValue(changedData, null);
if (!oldValue.Equals(newValue))
{
pi.SetValue(oldData, newValue, null);
}
}
}
I am not sure about the above method because it is so ugly method for updating data. From recent bug, it realizes me that if you update some property like Navigation Properties (related data from other table), it will remove current record from database. I don't understand why it happened. But it is very dangerous for me.
So, do you have any idea for this question to ensure me about updating data from ASP.NET MVC?
Thanks,