0

我正在使用 EF codefirst 处理 asp.net mvc。我正在尝试立即更新记录列表。喜欢,

foreach(var pat in listpats)
{
context.Entry<Patient>(pat).state=EntityState.Modified;
context.savechanges();
}

它对我来说工作正常。现在假设如果 listpats 包含 10 项,如果我在更新时在第 7 项出现异常。它将保存前 6 个项目。但是如果更新时没有发生错误,我想一次保存所有记录。如果发生任何错误意味着我应该回滚之前的所有更改。那么我如何使用 EF 代码优先模型来实现这一点。请指导我。

4

2 回答 2

0

If you've modified the entities in some other code then their state will be modified (within the same context) without you having to explicitly change it with a foreach loop and context.Entry(pat).state=EntityState.Modified.

So taking a step back, after you've modified all your patients entities a single call to context.SaveChanges() will automagically rollback on error.

Soooo to summarise, change all the patients entities and afterwards call context.SaveChanges() which will make EF propogate all the entities that have a modified state (the state change happens when you modify the entity) to the DB, context.SaveChanges() will handle simple cases like this with regards to rollback.

P.S. Your question is making me wonder if you've changed the patients in a different context and that's why your manually changing the current context' state.

于 2012-12-10T12:59:31.607 回答
0

您应该在 foreach 之外调用 SaveChanges():

foreach(var pat in listpats)
{
    context.Entry<Patient>(pat).state=EntityState.Modified;
}

context.SaveChanges();

这样,如果发生异常,所有内容都将回滚

于 2012-12-10T10:57:51.863 回答