Caleb Jares
Caleb Jares

Reputation: 6307

When to call SaveChanges

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();?

Upvotes: 7

Views: 7070

Answers (2)

Aviran Cohen
Aviran Cohen

Reputation: 5691

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();

Upvotes: 1

undefined
undefined

Reputation: 34238

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.

Upvotes: 11

Related Questions