实体框架 - 为什么将实体状态显式设置为已修改? [英] Entity Framework - Why explicitly set entity state to modified?

查看:23
本文介绍了实体框架 - 为什么将实体状态显式设置为已修改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

官方文档说要修改实体,我检索一个 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;

我不明白第 2 条和第 3 条语句的目的.如果我像第一个语句那样向框架询问实体,然后像在

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

这篇关于实体框架 - 为什么将实体状态显式设置为已修改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆