加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 实体框架DataContext关注 – 它是否在我的控制器中正确处

发布时间:2020-12-16 00:05:01 所属栏目:百科 来源:网络整理
导读:我已经交了一些代码,并且在控制器类中有一个属性,它包含初始化的数据库上下文. public class MyController: Controller{ protected AssetManagerContext db = new AssetManagerContext("ConnectionString"); // Actions...etc. [HttpGet] public ActionResul
我已经交了一些代码,并且在控制器类中有一个属性,它包含初始化的数据库上下文.

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);
    }
 }

大多数操作使用此Context而不处理它,我担心的是上下文保持开放.

>我是否需要关注此上下文未被显式关闭(通过.Dispose()或using {}语句
>如果我担心,我应该如何处理这种情况,因为变量是类的一部分并在操作中使用?

解决方法

Controller类有一个dispose方法.因此,在控制器中覆盖该方法并处理该上下文.

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

它将在上下文完成后自动调用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读