简体   繁体   English

DbSet <T> .Attach()方法是否将修改后的属性标记为“修改过”?

[英]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类(具有Id和Age的属性),我们需要将id为1的人的Age从29更改为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? entity.State 不变,并且没有属性被标记为已修改 ,但是EF内核仍然生成了一个Update SQL来设置[Age] = 30,如果实体状态不变并且EF内核认为没有属性修改,我感到困惑,那么EF核心不应该生成更新SQL吗?

and if I use Update() method instead of Attach() 如果我使用Update()方法而不是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. 实体的状态不会立即更新,而是在调用context.ChangeTracker.DetectChanges()时重新计算。

The property context.ChangeTracker.AutoDetectChangesEnabled is set to true by default. 默认情况下,属性context.ChangeTracker.AutoDetectChangesEnabled设置为true。 It means when context.SaveChanges() is called, context.ChangeTracker.DetectChanges() will be called first automatically, and then the states of entities are updated. 这意味着,当context.SaveChanges()被调用, context.ChangeTracker.DetectChanges()将首先被自动调用,然后实体的状态更新。

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. 根据文档https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.entityframeworkcore.dbset-1.update?view=efcore-2.1 ,实体对象的所有属性都将标记为“已Modified状态通过update方法本身,无论属性值是否真的被修改。 So the Update method is not using detecting change feature of EF, but set the sate of entity forcibly. 因此, Update方法不是使用检测EF的更改功能,而是强行设置实体的状态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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