3

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.

4

2 回答 2

3

在这个特定示例中,我将重用数据上下文:

  1. 避免建立新上下文的开销
  2. 保持实体附加,如果您计划在页面上重用它们,这很好

关于何时处理上下文没有硬性规定。这更多地取决于您如何使用数据:

  • 很少:如果您的操作是小型的、不频繁的和原子的,保持上下文活动可能会比按需创建一个上下文带来更多的开销/维护。把它放在一个using.
  • 正常:如果您定期更新和保存,请为每页创建一个上下文,但让页面处理它而不是传递它。提供性能和可维护性的最佳折衷。
于 2013-06-14T13:40:55.620 回答
1

只要您重用实体,就应该重用数据上下文实例。由于实体附加到特定上下文,因此您应该在查询和更新之间继续使用相同的上下文。

我个人对 Web 应用程序的偏好是在请求期间使用单个数据上下文并将其处理在 EndRequest 事件中。

于 2013-06-14T13:37:51.403 回答