For example, I have this class
class Person{
private int _id = int.MinValue;
private string _name = string.Empty;
private int _age = int.MinValue;
private string _city = string.Empty;
public string Id{ get { return _id ; } set { _id = value; } }
public string Name{ get { return _name; } set { _name = value; } }
public int Age{ get { return _age; } set { _age = value; } }
public string City{ get { return _city ; } set { _name = city; } }
}
and a list of Person that I show in a table. In this table there is an “edit in place/inline”: some Person’s property has a cell(td) in the table, so when I edit a cell, via javascript/jquery, I create the json object with the changed value and I send it to server. The json object contains only the property changed: if i edit “Name” the json object will be:
{"obj":{"Id":"1","Name":"Anna"}}
But the object Person to the server comes as
Id = 1, Name = "Anna", Age = 0, City = null
So the problem is: to execute an update stored procedure I must create the object with all original values to exceptions of the modified property. In this example, i want get this object:
Id = 1, Name = "Anna", Age = 25, City = "New York"
To create this object I use this method
public static TEntity CopyTo<TEntity>(this TEntity OriginalEntity, TEntity NewEntity){
PropertyInfo[] oProperties = OriginalEntity.GetType().GetProperties();
foreach (PropertyInfo CurrentProperty in oProperties.Where(p => p.CanWrite))
{
if (CurrentProperty.GetValue(OriginalEntity, null) == null)
{
CurrentProperty.SetValue(OriginalEntity, CurrentProperty.GetValue(NewEntity, null), null);
}
}
return OriginalEntity;
}
If new object Person has a property with null value then I take the orginal value from the original Person (NewEntity). This way doesn’t work with number because from client to server the Age property become 0 and not null.
How I can to resolve this problem? To consider that I can not use:
- nullable type because I should to modify so many lines of code in the whole project;
- the table may not contain all the properties of Person, so I can’t create the entire object in javascript and then to change only the value modified.
I hope I was clear enough with my bad english
k; if I re-phrase: you want to copy all properties that have non-null values onto an existing object. Well, the first issue (as you note) is that you can’t have an
intthat isnull. Fortunately, you can fix that by simply taking the pragmatic step of makingAgeandIdaNullable<int>, akaint?:So now we just have the “copy all non-null values”. For that, look at this existing answer, which is a bit like your reflection approach, but it uses IL to be stupidly fast.
Example usage:
It could also be tweaked to do an in-place merge over one of the existing objects.