I am writing bugfix code for a legacy ASP.NET application which uses Entity Framework 5. I am taking user input and update my entities using the new data.
My entities do not change much, but still I currently take all values from the UI and set it on the entities like so:
myEntityUnit.MyEntityAddress.AddressLine1 = AddressLine1; //Update with potentially the same value
This works functionally, but I also causes much of Database traffic, even for the non-changed properties since EF remembers those updates in it's change tracker. The property of the above actually looks like:
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public global::System.String AddressLine1
{
get
{
return _AddressLine1;
}
set
{
OnAddressLine1Changing(value);
ReportPropertyChanging("AddressLine1");
_AddressLine1 = StructuralObject.SetValidValue(value, true, "AddressLine1");
ReportPropertyChanged("AddressLine1");
OnAddressLine1Changed();
}
}
So, whenever the setter is accessed, even with the same value, a change is detected.
How to best avoid this, on some (dozens) properties, on some entities only (too keep bugfix changes minimal)?
I've come up with some simple check conditions like so, but this feels clumsy and overly verbose:
if (profilingEnterpriseUnit.ProfilingAddress.AddressLine1 != AddressLine1) {
profilingEnterpriseUnit.ProfilingAddress.AddressLine1 = AddressLine1;
}
Is there a way to write a function that update a property, via it's setter, only when the value differs using the getter?
Note: I have looked into Passing properties by reference in C# but the solution is not using getters at all and still is quite verbose both in usage and code.