在MVC中使用语句处理数据库上下文 [英] Disposing Database context with using statement in MVC
问题描述
public ActionResult SomeAction(){
using(var DB = new DatabaseContext {
....
return View();
}
}
返回前是否必须关闭using语句?或者它将按照我使用的方式妥善处理。
返回前是否必须关闭using语句?或者它会按照我使用的方式妥善处理?
它将自动为您处理。您可以参考此回答了解更多信息但是, Dispose
方法被调用,但执行语句的语句,除非是突然的整个过程终止。最常见的情况是:
- 块内的
返回
- 块内抛出异常(而不是被捕获)
- 自然地到达块的末尾
基本上使用语句的语句主要是一个
尝试的语法糖
/ finally
block - 和 finally
具有相同的属性。
从 C#4规范的8.13节:
使用语句的
分为三个部分:获取,使用和处置。资源的使用被隐含地包含在包含
finally
子句的try
语句中。finally
clause处理资源。
I'm using entity framework in my MVC website and I'm disposing my database context using using-statement. Now my question is if I close using statement after return, would the database context disposed properly or not. Ex:
public ActionResult SomeAction(){
using (var DB = new DatabaseContext()){
....
return View();
}
}
Do I have to close the using statement before return? Or it would be disposed properly in the way I'm using it.
Do I have to close the using statement before return? Or it would be disposed properly in the way I'm using it?
It will be automagically disposed for you. You can refer to this answer for more information .The Dispose
method is called however the using
statement is executed, unless it was an abrupt whole-process termination. The most common cases are:
- A
return
within the block - An exception being thrown (and not caught) within the block
- Reaching the end of the block naturally
Basically a using
statement is mostly syntactic sugar for a try
/finally
block - and finally
has all the same properties.
From section 8.13 of the C# 4 specification:
A
using
statement is stranslated into three parts: acquisition, usage, and disposal. Usage of the resource is implicitly enclosed in atry
statement that includes afinally
clause. Thisfinally
clause disposes of the resource.
这篇关于在MVC中使用语句处理数据库上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!