何时调用SaveChanges [英] When to call SaveChanges
问题描述
说我有在Controller
中调用的类似内容:
Say I have something like this that is called in Controller
:
using (var context = new SqlContext())
{
context.Items.Add(new Item("item1"));
}
我应该打context.SaveChanges();
吗?
推荐答案
实体框架使用DbContext实现工作单元模式,这意味着您定义了要对数据库执行的操作的包,然后调用save更改进行传播将它们全部一次存储到数据库中.所有操作都将在一个事务中执行(对于单个saveChanges调用),这意味着全部或全部都不会立即传播到数据库.
entity framework implements a unit of work pattern with DbContext this means that you define a package of things you want to do to your database and then call save changes to propogate them all to the database at once. All operations will be executed within a single transaction (for a single saveChanges call) which means that either all or none will be propogated to the database at once.
在调用保存更改之前,更改将应用于本地跟踪图,而不应用于数据库本身,直到调用savechanges.
Before calling save changes, the changes are applied to your local tracking graph but not to the database itself until savechanges is called.
这篇关于何时调用SaveChanges的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!