问题
Say I have something like this that is called in Controller
:
using (var context = new SqlContext())
{
context.Items.Add(new Item("item1"));
}
Should I be calling context.SaveChanges();
?
回答1:
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.
Before calling save changes, the changes are applied to your local tracking graph but not to the database itself until savechanges is called.
回答2:
yes.
every change you make won't be saved until context.SaveChanges();
is called.
Note that if you will have an object from other DbContext (which is absolutly not the situation you gave) you should need to change the entity state explicitly by using these lines of code instead:
Item item = new Item("item1")
db.Entry(item).State = EntityState.Modified;
db.SaveChanges();
来源:https://stackoverflow.com/questions/14269765/when-to-call-savechanges