Danny Simmons on “Context Lifetimes — Dispose or Reuse?”

People are more willing to believe guidance from someone at Microsoft than someone outside of Microsoft, therefore I’m happy that Danny has written a blog post on a topic he has answered a few times in the forums and I have pointed to previously as “evidence” in my own blog posts.

This blog post addresses the question about how long to keep an objectcontext around. Danny reiterates what he has advised in the forums:

Standard cases:

Websites/Web services – shortest lifetime as possible. Create the context, do query/savechanges, kill the context

Client apps (winforms, wpf, console) – it’s okay to leave the context hanging around. IT was designed for that purpose and will make change tracking and updates to the db a lot easier.

Edge cases:

Huge amounts of data to deal with for updates? Handle them in batches. You might want t take a look at the experiments with updating that Alex James has been writing about (see below for links) for a different look at updates.

Client app with data that you would like to cache combined with data that changes: for example, a list of product categories that doesn’t change much as well as order data that changes frequently. I’ve seen the back and forth discussions of this scenario in the forums. Danny recommends using a single context and how to manage that data within that context.

Read all the details here

Alex James blog post series:

  • Rolling your own SQL Update on top of the Entity Framework – Part 4
  • Rolling your own SQL Update on-top of the Entity Framework – Part 3
  • Rolling your own SQL Update on top of the Entity Framework – Part 2
  • Rolling your own SQL Update on-top of the Entity Framework – Part 1
  •   Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!  

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.