0

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.

Marcel
  • 15,039
  • 20
  • 92
  • 150
  • It says here only the properties marked with isModified = true will be saved to dB https://learn.microsoft.com/en-us/ef/ef6/saving/change-tracking/property-values – estinamir Apr 05 '20 at 03:49
  • @bestinamir In practice, I experienced DB accesses even when set to the same value. Any access seems to count as "change" here. – Marcel Apr 06 '20 at 06:19
  • May be you’ll get different result if you upgrade to EF6 which they say backward compatible https://www.pluralsight.com/blog/software-development/entity-framework-6-tips – estinamir Apr 06 '20 at 18:01
  • @bestinamir I would, but since this only a bugfix release, this is out of scope, unfotunately. – Marcel Apr 07 '20 at 05:34

0 Answers0