I had some code for inserting some rows that wasn't working:
using (MyDbContext context = new MyDbContext()) {
foreach (Order o in FormOrders) { //That's a List<T> that got generated based on a web form
context.Orders.Add(o);
}
context.SaveChanges();
}
I finally figured out how to make it work:
foreach (Order o in FormOrders) {
context.Orders.Add(o);
context.SaveChanges();
}
However, I realize that's not very efficient. Granted, the most Orders that will ever get inserted at one time is about 40, but I'm still interested in using best practices as much as I can.
I'm guessing code snippit #1 didn't work because o
is out of scope of the point that SaveChanges()
is called, but I don't understand how this works well enough to be sure, and I definitely don't understand it enough to figure out what a better way is.
Also, I have heard that you're supposed to use a new instance of your DbContext for every row, which would be even less efficient to implement in the above case. Is that true?
EDIT
忽略这个问题。两个版本似乎都有效。我不知道是什么问题。我不会删除它,因为其他人可能会发现某些评论/答案很有用。