c# – 使用实体框架而不使用语句的缺点?
发布时间:2020-12-16 01:52:52 所属栏目:百科 来源:网络整理
导读:有很多像这样的代码块: public class SomeController : Controller{ DbEntities entity = new DbEntities(); public ActionResult Add() { entity.someOperations... return View(); } public ActionResult Edit() { entity.someOperations... return View(
有很多像这样的代码块:
public class SomeController : Controller { DbEntities entity = new DbEntities(); public ActionResult Add() { entity.someOperations... return View(); } public ActionResult Edit() { entity.someOperations... return View(); } public ActionResult Detail() { entity.someOperations... return View(); } public ActionResult Detail() { entity.someOperations... return View(); } ..... 我应该改变这样的方法吗?: public class SomeController : Controller { public ActionResult Add() { using(DbEntities entity = new DbEntities()) { entity.someOperations... } return View(); } ..... 在EF中不使用using语句有什么问题?或者最好的方法是什么?另外,如果我们使用using语句代码块也会增长. 谢谢… 解决方法
使用声明方法是您在上面提出的两种方法中最好的.使用这种方法,可以确保ObjectContext在使用后关闭并处理掉.
使用您的其他方法,可以假设ObjectContext可以保持未闭合,从而占用与数据库的连接.要查看此操作,请尝试使用其他方法创建示例应用程序,然后使用EFProfiler对其进行概要分析并观察ObjectContext打开的数量,同时关闭的数量将明显减少. 我最近参与了一个项目,该项目在高使用率下遇到了数据库问题,采用了你的第二种模式(你可以看到我的问题HERE).由于我没有足够的时间在项目/代码库上太大,我没有选择切换到using语句方法.相反,我实现了以下操作来手动强制在Global.asax中的End_Request上处理ObjectContext(我在我的BusinessLayerService的静态实例上有一个DbContext的实例: protected void Application_EndRequest(object sender,EventArgs e) { BusinessLayerService.Instance.Dispose(); BusinessLayerService.Instance = null; } 但是,如果您从项目开始有选项:我强烈建议使用使用模式 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |