我应该一次或每次更改后调用SaveChanges吗? [英] Should I call SaveChanges once or after each change?
本文介绍了我应该一次或每次更改后调用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?
推荐答案
这要视情况而定.
- 进行每次更改-如果您希望每个保存都在其自己的事务中运行并且独立于其他更改,请在循环中或进行更改后运行保存.请注意,如果代码稍后出现故障,则已发生的更改将保留并不会回滚.由于您要往返于数据存储的次数更多,因此这也具有较高的性能成本.在某些情况下,可以保证可以使用此方法,这里有两个简单的示例:
- 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:
- 您想将长时间运行的操作的进度追溯到数据存储中,并在此之前包括所有更改.
- 您要批量保存代码正在处理的大块数据,并且代码知道如何在发生故障的最后一个保存点之后采取措施.
这篇关于我应该一次或每次更改后调用SaveChanges吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文