Should I call SaveChanges once or after each change?

I need to make a few changes to 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();

Shoul I call SaveChanges at the end or every time I make changes?

+4
source share
3 answers

It depends.

  • . , , . , , , , . , . , , :
    • .
    • , , , .
  • . , , , , - , . , ( ), . , . , , , , .
+4

db

+1

1) .

public ActionResult Create() 
{ 
     db.ValueStreamProduct.Add(vsp);
     db.tbl.Add(tbl2);
     db.tbl.Add(tbl3);

     // only one time you can call savechanges()
     db.SaveChanges();
 }

2) ValueStreamProduct tbl2.

But you need to get your last inserted record id for the second table. code like this

 public ActionResult Create() 
 {
     db.ValueStreamProduct.Add(vsp); 
     db.SaveChanges();

     // getting last inserted record Id from ValueStreamProduct table.
     tbl2.Column = vsp.Id

     db.tbl.Add(tbl2);
     db.tbl.Add(tbl3);

     db.SaveChanges();
  }
0
source

Source: https://habr.com/ru/post/1656829/


All Articles