Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Core updating unchanged fields

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
like image 330
Chris Avatar asked Jan 03 '23 09:01

Chris


1 Answers

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).

like image 115
Ivan Stoev Avatar answered Jan 23 '23 01:01

Ivan Stoev