更新需要EntityState.Modified吗? [英] Is EntityState.Modified required for an update?

查看:60
本文介绍了更新需要EntityState.Modified吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在更新记录用途时,我见过很多人:

I've seen a lot of people when updating a record use:

...
ms.Status = status;
db.Entry(ms).State = EntityState.Modified;
db.SaveChanges();

这行是必需的吗?没有它,我就可以进行更新.

Is this line required? I was able to do an update without it.

db.Entry(ms).State = EntityState.Modified;

我想知道,如果上下文已经知道它应该在不显式指定的情况下更新该记录,那么为什么还要麻烦地显式指定它呢?

I was wondering what this statement is actually used for if the context already knows it should update that record without you specifying it explicitly then why bother specifying it explicitly?

推荐答案

如果在EF上下文未跟踪实体(实体已分离)时完成了对实体的更改,则是必需的.如果从上下文中加载实体,请对其进行修改并将其保存在与使用实体相同的上下文中,因为EF会跟踪更改并自动设置状态.

It is required if your changes in the entity was done when entity was not tracked by EF context (the entity was detached). If you load entity from the context, modify it and save it by the same context you don't need to use it because EF will track changes and set the state automatically.

这篇关于更新需要EntityState.Modified吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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