AcceptAllChanges 导致实体框架...不接受更改?
我正在使用.NET 3.5 SP1。我有一个简单的脚本来删除一些实体。
var people = (from Person p in context.People
where p.FirstName == "Testy" &&
p.LastName == "McTesterson"
select p).ToList();
people.ForEach(p => context.DeleteObject(p));
//context.AcceptAllChanges();
context.SaveChanges();
如果我取消注释 AcceptAllChanges()
,则不会删除对象。如果我保留它的评论,实体将被删除。为什么 EF 会有这样的表现?这似乎适得其反。
I'm using .NET 3.5 SP1. I have a simple script that deletes some entities.
var people = (from Person p in context.People
where p.FirstName == "Testy" &&
p.LastName == "McTesterson"
select p).ToList();
people.ForEach(p => context.DeleteObject(p));
//context.AcceptAllChanges();
context.SaveChanges();
If I uncomment AcceptAllChanges()
, the objects are not deleted. If I keep it commented, the entities are deleted. Why does EF behave like this? It seems counter productive.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这就是
AcceptAllChanges
的行为。接受更改会“重置”ObjectContext
的内部状态。这意味着添加或修改的所有实体都设置为“未更改”状态,并且删除的所有实体都从上下文中分离。相比之下,
SaveChanges
方法会迭代ObjectContext
的内部状态,并为状态为“已添加”的每个实体创建 INSERT db 命令,为每个实体创建 UPDATE db 命令每个处于“已修改”状态的实体和每个处于“已删除”状态的实体的 DELETE db 命令。SaveChanges
默认情况下会在执行所有命令后接受所有更改。如果您在
SaveChanges
之前运行AcceptAllChanges
,则会清除所有更改,并且数据库中不会执行任何操作。该方法存在的原因是您可以关闭默认的 SaveChanges 行为;在这种情况下,您必须在执行SaveChanges
后手动接受更改。否则,下次调用SaveChanges
将再次执行更改。That is the behavior of
AcceptAllChanges
. Accepting changes "resets" the internal state ofObjectContext
. It means that all entities which were added or modified are set to "unchanged" state and all entities which were deleted are detached from the context.In contrast,
SaveChanges
method iterates the internal state ofObjectContext
and creates INSERT db commands for each entity with a state of added, UPDATE db command for each entity in modified state and DELETE db command for each entity in deleted state.SaveChanges
by default accepts all changes after it executes all commands.If you run
AcceptAllChanges
beforeSaveChanges
you clear all changes and there is nothing to execute in DB. The reason why this method exists is that you can turn off defaultSaveChanges
behavior; in such a case, you must accept changes manually after you executeSaveChanges
. Otherwise the next call toSaveChanges
will execute the changes again.