Entity Framework Core updating unchanged fields

audit.net entity-framework-core

Question

I'm not sure if this is a question about Entity Framework, or how the audit.net library works, but I was guessing it was with how I was performing updates with EF. My goal is to capture only actual changes to the record, but it's capturing everything as change, even if the old and new values are identical.

Basically to simplify it as much as possible, if I do

var existing = context.Appl.FirstOrDefault(a => a.Id == id);
context.Appl.Update(existing);
context.SaveChanges();

(Changing nothing)

The Audit.Net change log says every single field was changed, and looks like

   "Changes": [
      {
        "ColumnName": "FOO",
        "OriginalValue": "",
        "NewValue": ""
      },
      ..... many more
1
4
5/15/2018 3:11:39 PM

Accepted Answer

My goal is to capture only actual changes to the record

Then you should not use the Update method.

According to the Update method documentation:

Begins tracking the given entity in the Modified state such that it will be updated in the database when SaveChanges() is called.

All properties of the entity will be marked as modified. To mark only some properties as modified, use Attach(Object) to begin tracking the entity in the Unchanged state and then use the returned EntityEntry to mark the desired properties as modified.

The main usage case for Update method is to perform a so called forced update when working with Disconnected Entities. Since your existing entity is retrieved from the context (or in other words, is tracked by the context), hence all you need is to set the new values. Change tracker will detect if there are actual property changes and will issue UPDATE command with only modified values (or no UPDATE command at all if all current values are equal to the original values).

7
5/15/2018 4:39:02 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow