实体框架的DataContext关注 - 它是正确得到我的控制器处理? [英] Entity Framework DataContext Concern - Is it getting disposed properly in my controller?
问题描述
我已经交到了一些code,并在控制器类有一个保存初始化数据库上下文的属性。
公共类myController的:控制器
{
保护AssetManagerContext DB =新AssetManagerContext(的ConnectionString);
//动作...等。 [HTTPGET]
公众的ActionResult编辑(INT ID)
{
MyAsset myAsset = db.Assets.Find(ID); //使用和处置不
返回查看(myAsset);
}
}
大多数的行动使用此背景下不设置它,我关心的是,上下文处于打开状态。
-
我需要关注这个方面没有明确关闭(通过.Dispose()或使用{}语句
-
如果我担心,我应该如何处理这种情况,因为变量是类的一部分,并在行动中使用?
控制器类有处置的方法。所以覆盖你的控制器的方法和处理这方面。
保护覆盖无效的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.
Do I need to be concerned about this context not being explicitly closed (either by .Dispose() or a using {} statement
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屋!