Yes there are a lot of similiar questions but hear me out.
I have a scenario where I iterate over items and either Update
or Add
them. Lets take this for example
// var ctx = ctxFactory.Get();
foreach(var book in cart)
{
// var ctx = ctxFactory.Get();
var dbBook = ctx.Books.FirstOrDefault(p => p.ISBN == product.ISBN);
if (dbBook == null)
{
ctx.Add(book);
}
else
{
dbBook.Excerpt = book.Excerpt;
ctx.Update(dbBook);
}
ctx.SaveChanges()
}
My question is: Should I create the context in- or outside of the loop?
The DbContext
should be created the least amount of times possible and should be reused the most times possible.
That being, said I think that this is what you're looking for:
using (var ctx = ctxFactory.Get())
{
var dbBook = ctx.Books.FirstOrDefault(p => p.ISBN == product.ISBN);
foreach (var book in cart)
{
if (dbBook == null)
{
ctx.Add(book);
}
else
{
dbBook.Excerpt = book.Excerpt;
ctx.Update(dbBook);
}
}
ctx.SaveChanges();
}
Also as it is a disposable object you should always dispose of it or encapsulate its use with a using statement, as I have done in my example.