Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 704
Caleb Jares Avatar asked Jan 11 '13 00:01

Caleb Jares


People also ask

When should I call SaveChanges?

If you need to enter all rows in one transaction, call it after all of AddToClassName class. If rows can be entered independently, save changes after every row.

When would you use SaveChanges false AcceptAllChanges ()?

SaveChanges(false) does the actual updating to the database, while AcceptAllChanges() tells EF, "Okay, you can forget which things need to be saved, because they've been sucessfully saved." If SaveChanges(false) fails, AcceptAllChanges() will never be called and EF will still consider your object as having properties ...

Does SaveChanges commit?

In Entity Framework, the SaveChanges() method internally creates a transaction and wraps all INSERT, UPDATE and DELETE operations under it. Multiple SaveChanges() calls, create separate transactions, perform CRUD operations and then commit each transaction.

How does DB SaveChanges work?

Basically the db. SaveChanges() method is used by Entity Framework to save current changes to the database and ModelState represents validation errors when e.g. the model is not valid.


2 Answers

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.

like image 69
Not loved Avatar answered Sep 30 '22 09:09

Not loved


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();
like image 27
Aviran Cohen Avatar answered Sep 30 '22 08:09

Aviran Cohen