实体框架的DataContext关注 - 它是正确得到我的控制器处理? [英] Entity Framework DataContext Concern - Is it getting disposed properly in my controller?

查看:114
本文介绍了实体框架的DataContext关注 - 它是正确得到我的控制器处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经交到了一些code,并在控制器类有一个保存初始化数据库上下文的属性。

 公共类myController的:控制器
{
    保护AssetManagerContext DB =新AssetManagerContext(的ConnectionString);
    //动作...等。    [HTTPGET]
    公众的ActionResult编辑(INT ID)
    {
        MyAsset myAsset = db.Assets.Find(ID); //使用和处置不
        返回查看(myAsset);
    }
 }

大多数的行动使用此背景下不设置它,我关心的是,上下文处于打开状态。


  1. 我需要关注这个方面没有明确关闭(通过.Dispose()或使用{}语句


  2. 如果我担心,我应该如何处理这种情况,因为变量是类的一部分,并在行动中使用?



解决方案

控制器类有处置的方法。所以覆盖你的控制器的方法和处理这方面。

 保护覆盖无效的Dispose(BOOL处置)
{
   base.Dispose(处置);
   db.Dispose();
}

这将背景下得到完成后,被自动调用。

I've been handed some code, and in the controller class there is a property that holds the initialized database context.

public class MyController: Controller
{
    protected AssetManagerContext db = new AssetManagerContext("ConnectionString");
    // Actions...etc.

    [HttpGet]
    public ActionResult Edit(int id)
    {
        MyAsset myAsset = db.Assets.Find(id); // Used and not disposed
        return View(myAsset);
    }
 }

Most of the actions use this Context without disposing it, and my concern is that the context is left open.

  1. Do I need to be concerned about this context not being explicitly closed (either by .Dispose() or a using {} statement

  2. If I should worry, how should I handle this situation, since the variable is part of the class and used across actions?

解决方案

The Controller class has a method of dispose. So override that method in your controller and dispose that context.

protected override void Dispose(bool disposing)
{
   base.Dispose(disposing);
   db.Dispose();
}

It will be called automatically after the context get completed.

这篇关于实体框架的DataContext关注 - 它是正确得到我的控制器处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆