简体   繁体   中英

DbSet<T>.Attach() method does't mark modified properties as “modified”?

let's say we have a Person class(with properties of Id and Age), let's say we need to change the Age of a person whose id is 1 from 29 to 30,

Person p = new Person(){ Id = 1 }  //Age is default to 0 here, but does't matter, because it is going to be changed later
var entity = context.Persons.Attach(p);
p.Age = 30;

Console.WriteLine("entity state:" + entity.State);
foreach (var modifiedProperty in entity.Properties.Where(p => p.IsModified))
{
   Console.Write($"The {modifiedProperty.Metadata.Name} property is marked as modified");
}
context.SaveChanges();

and the output shows:

the entity.State is unchanged and no properties are marked as modified , but still EF core generated an Update SQL to set [Age] = 30, I'm confused, if the entity state is unchanged and EF core think there is no property modifications, then EF core shouldn't generate an Update SQL?

and if I use Update() method instead of Attach()

...
var entity = context.Persons.Update(p);
...

then everything is normal, the Entity status is modified, Age is identified as modified property?

The states of entities will not be updated immediately but recalculated when context.ChangeTracker.DetectChanges() is called.

The property context.ChangeTracker.AutoDetectChangesEnabled is set to true by default. It means when context.SaveChanges() is called, context.ChangeTracker.DetectChanges() will be called first automatically, and then the states of entities are updated.

According to the document https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbset-1.update?view=efcore-2.1 , all properties of the entity object will be marked in Modified state by the update method itself, no matter whether the property value is really modified. So the Update method is not using detecting change feature of EF, but set the sate of entity forcibly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM