Given the following function the variable currentModel is already the modified model that I want to update and it might have some properties different from the ones in the database and this function correctly updates the modified values.
Now I want to track the changes made before the update, the problem is that the ChangeTracker
is detecting all properties as modified even when only one is acctualy different from the original model.
Is there a way to use ChangeTracker
while also updating the statement with EntityState.Modified
Related links:
DbEntityEntry.GetDatabaseValues Method
DbPropertyValues.SetValues Method
CodePudding user response:
It is possible to copy the entity's values from a other class instance as follows :
public void SaveCustomer(Client currentModel)
{
var objFromDbAct = _db.Clients.Local.FirstOrDefault(c => c.Recid == currentModel.Recid);
if (objFromDbAct == null)
{
_db.Update(currentModel);
}
else
{
var preEntity = _db.Entry(objFromDbAct);
preEntity.CurrentValues.SetValues(currentModel);
}
_db.ChangeTracker.DetectChanges();
string trackChanges = _db.ChangeTracker.DebugView.LongView;
_db.SaveChanges();
}
trackChanges value :
Client {Recid: 1} Modified
Recid: 1 PK
Addr1: 'Address 1'
Addr2: 'Address 2'
Zip: 'Modified' Modified Originally 'Zip'
And the SQL executed by SaveChanges
:
UPDATE [Clients] SET [Zip] = @p0
WHERE [Recid] = @p1;