Is EntityState.Modified required for an update?

前提是你 提交于 2021-02-20 05:39:29

问题


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?


回答1:


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.




回答2:


From my understanding this only needs to be used if the entity has been re-attached to the context. Otherwise no.



来源:https://stackoverflow.com/questions/9718129/is-entitystate-modified-required-for-an-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!