I have something that I call
It was just added to a database
var konsultant = uczestnik.Konsultanci; uczestnik.Konsultanci = null; // null attached object and reuse it's ID later on for SAVE purposes uczestnik.KonsultantNazwa = konsultant.KonsultantNazwa; uczestnik.Szkolenie = null; // null attached object and reuse it's ID later on for SAVE purposes uczestnik.SzkolenieID = szkolenie.SzkolenieID; context.SzkolenieUczestnicies.AddObject(uczestnik); context.SaveChanges(); context.Detach(uczestnik); // detatch to prevent Context problems uczestnik.Szkolenie = szkolenie;// reassign for use in ObjectListView uczestnik.Konsultanci = konsultant; // reassign for use in ObjectListView
Once it has been saved, the user may return to the ObjectListView and edit the value as desired (one value from multiple to be exact). If I look at the value's entity state, it is in the state of Unchanged, therefore calling. affix and. SaveChanges() has no effect. I possess
However, there is little use in doing so if nothing has changed.
context.SzkolenieUczestnicies.Attach(uczestnik); //context.ObjectStateManager.ChangeObjectState(uczestnik, EntityState.Modified); context.SaveChanges();
How can I recognize a change and stop unneeded traffic (I can see a scenario where the object holding the five megabyte files has not changed)?
It is illogical. Unless the Entity is intelligent enough to recognize that just one of the 15 fields was altered and modify only that field?
entity, which the context does not monitor. In this scenario, it is your responsibility to determine when the object has changed and to notify the context of those changes using
. You must thus keep track of which user edited or added anything to your entities. Implement, for instance,
INotifyPropertyChanged (if you are using EntityObject based entities this interface should be already implemented).
If an entity is removed from its context, it cannot be determined what has changed unless the original object is loaded from the database, self-tracking entities are used, or the tracking is manually managed.
Reloading the entity will allow you to utilize
var originalEntity = context.MyEntities.Single(e => e.Id == detachedEntity.Id); context.MyEntities.ApplyCurrentValues(detachedEntity); context.SaveChanges();
By using this approach, attributes with differing values between the original and detached entities are marked as changed.
will provide a UPDATE statement that only contains the attributes that have changed. if no property changed,
has no effect.
You will save one unneeded UPDATE statement, but you are not entirely free of "unnecessary traffic" since you must load the original object.