我应该一次或每次更改后调用SaveChanges吗? [英] Should I call SaveChanges once or after each change?

查看:246
本文介绍了我应该一次或每次更改后调用SaveChanges吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在控制器的数据库中进行几处更改.

I need to make several changes in my database in my controller.

foreach (var valueStream in model.ListValueStream)
{
    ValueStreamProduct vsp = new ValueStreamProduct(valueStream.Id, product.Id);
    db.ValueStreamProduct.Add(vsp);
}
db.SaveChanges();

我应该在结束时还是每次进行更改时调用SaveChanges?

Should I call SaveChanges at the end or each time I make changes?

推荐答案

这要视情况而定.

  1. 进行每次更改-如果您希望每个保存都在其自己的事务中运行并且独立于其他更改,请在循环中或进行更改后运行保存.请注意,如果代码稍后出现故障,则已发生的更改将保留并不会回滚.由于您要往返于数据存储的次数更多,因此这也具有较高的性能成本.在某些情况下,可以保证可以使用此方法,这里有两个简单的示例:
  1. With each change - If you want each save to run in its own transaction and be independent of other changes then run the save in the loop or after you make a change. Note that if there is a failure later in the code then the changes that have already occurred are persisted and will not be rolled back. This also has a higher performance cost as you are making more round trips to the data store. There are situations which could warrant this use though, here are 2 quick examples:
  1. 您想将长时间运行的操作的进度追溯到数据存储中,并在此之前包括所有更改.
  2. 您要批量保存代码正在处理的大块数据,并且代码知道如何在发生故障的最后一个保存点之后采取措施.

  • 所有更改之后-如果您希望获得更高的性能,并且希望所有保存通过或失败,并在出现任何失败时将其回滚,则可以在循环外或循环结束时运行它们.代码块的末尾.现在,如果代码出现故障(保存更改调用之前或之后的任何地方),则所有更改都不会持久保存到存储中.在大多数情况下,这是理想的行为,因为它可以确保您的数据存储处于良好状态.这可能是您希望代码执行的更多时候了.
  • After all changes - If you want more performance and you want all saves to either pass or fail and be rolled back if there is any failure then run them at the end outside the loop or at the end of the code block. Now if there is a failure in the code (anywhere before or on the save changes call) no changes will be persisted to the store. In most situations this is desirable behavior as it ensures a good state for your data store. More frequently than not this is probably what you want your code to do.
  • 这篇关于我应该一次或每次更改后调用SaveChanges吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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