I need to make several changes in 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();
Should I call SaveChanges at the end or each time I make changes?
It depends.
It depends, on your requirement
Requirement 1) three table are independent.
public ActionResult Create()
{
db.ValueStreamProduct.Add(vsp);
db.tbl.Add(tbl2);
db.tbl.Add(tbl3);
// only one time you can call savechanges()
db.SaveChanges();
}
Requirement 2) ValueStreamProduct table Id is necessary for tbl2.
But, you need to get your last inserted record's Id for second table. code like this
public ActionResult Create()
{
db.ValueStreamProduct.Add(vsp);
db.SaveChanges();
// getting last inserted record's Id from ValueStreamProduct table.
tbl2.Column = vsp.Id
db.tbl.Add(tbl2);
db.tbl.Add(tbl3);
db.SaveChanges();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With