Tom Gullen
Tom Gullen

Reputation: 61719

When to reuse data contexts

I've been reading a bit of confusing and conflicting advice on this.

Given the following example methods:

using(var db = new MainContext())
{
    var q = db.tblArcadeGames;
    foreach (var game in q)
    {
        UpdateGameStats(game);
    }
}

public void UpdateGameStats(ArcadeGame game)
{
    using(var db = new MainContext())
    {
        // Do some queries and updates etc
    }
}

Should the data context created initally be passed as a parameter to UpdateGameStats as follows:

using(var db = new MainContext())
{
    var q = db.tblArcadeGames;
    foreach (var game in q)
    {
        UpdateGameStats(game, db);
    }
}

public void UpdateGameStats(ArcadeGame game, MainContext db)
{
        // Do some queries and updates etc
}

Is reusing a data context always best practise? Should only one be created on each page which is reused? Or should a new one be created each time?

Reusing data contexts appears to me to create a situation where it's harder to maintain and modularise code in some instances.

Upvotes: 3

Views: 171

Answers (2)

SlightlyCuban
SlightlyCuban

Reputation: 3255

In this specific example, I'd reuse the data context:

  1. Avoids overhead of establishing a new context
  2. Keeps entities attached, which is good if you plan on reusing them on the page

There isn't a hard, fast rule on when to dispose of your contexts. It more depends on how you're using your data:

  • Rarely: if your operations are small, infrequent, and atomic, keeping a context alive might introduce more overhead/maintenance than creating one on demand. Just put it in a using.
  • Normal: if you're updating and saving on a regular basis, make a context per page, but have the page dispose it instead of passing it around. Gives the best tradeoff of performance and maintainability.

Upvotes: 3

Knaģis
Knaģis

Reputation: 21475

You should reuse the data context instance as long as you are reusing the entities. Since the entities are attached to a specific context, you should keep using the same context between query and update.

My personal preference for web application is to use a single data context for the duration of the request and dispose it in EndRequest event.

Upvotes: 1

Related Questions