在MVC中使用语句处理数据库上下文 [英] Disposing Database context with using statement in MVC

查看:307
本文介绍了在MVC中使用语句处理数据库上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的MVC网站中使用实体框架,我使用using-statement处理我的数据库上下文。现在我的问题是如果我关闭使用语句返回后,数据库上下文是否妥善处理。例如:

  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 a try statement that includes a finally clause. This finally clause disposes of the resource.

这篇关于在MVC中使用语句处理数据库上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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