Reputation: 61719
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
Reputation: 3255
In this specific example, I'd reuse the data context:
There isn't a hard, fast rule on when to dispose of your contexts. It more depends on how you're using your data:
using
.Upvotes: 3
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