How often should I create a DbContext?

ef-core-3.0 entity-framework-core

Question

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?

1
1
10/17/2019 11:40:54 PM

Popular Answer

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.

1
10/18/2019 8:36:49 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow