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(); } 它将在上下文完成后自动调用. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |