问题描述
官方文档说修改一个实体,我检索一个DbEntityEntry对象,并使用属性函数,或者我将其状态设置为修改。它使用以下示例
The official documentation says to modify an entity I retrieve a DbEntityEntry object and either work with the property functions or I set its state to modified. It uses the following example
Department dpt = context.Departments.FirstOrDefault();
DbEntityEntry entry = context.Entry(dpt);
entry.State = EntityState.Modified;
我不明白第二和第三个声明的目的。如果我要求一个实体的框架,如第一个声明,然后修改POCO,如
I don't understand the purpose of the 2nd and 3rd statement. If I ask the framework for an entity like the 1st statement does and then modify the POCO as in
dpt.Name = "Blah"
如果我再向EF请求SaveChanges(),那么实体具有 MODIFIED的状态(我通过快照跟踪猜测,这不是代理),并且更改被持久化,而不需要手动设置状态。我在这里缺少一些东西吗?
If I then ask EF to SaveChanges(), the entity has a status of MODIFIED (I'm guessing via snapshot tracking, this isn't a proxy) and the changes are persisted without the need to manually set the state. Am I missing something here?
推荐答案
在你的场景中,你确实不必设置状态。更改跟踪的目的是发现您已更改附加实体上的值并将其置于修改状态。手动设置状态对于分离的实体(实体加载而无需更改跟踪或在当前上下文之外创建)的情况下很重要。
In your scenario you indeed don't have to set the state. It is purpose of change tracking to find that you have changed a value on attached entity and put it to modified state. Setting state manually is important in case of detached entities (entities loaded without change tracking or created outside of the current context).
这篇关于实体框架 - 为什么要明确地设置实体状态来修改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!