[英]Drawbacks with using entity framework without using statement?
有很多像這樣的代碼塊:
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-statement
有什么問題? 或者最好的方法是什么? 另外,如果我們使用using-statement
代碼塊也會增長。
謝謝...
如果使用using語句,上面的示例中沒有大問題,但是當dbContext是局部變量時,很難為這樣的代碼編寫單元測試。
如果你不遵循任何設計模式,如Repository,Unit of Work,你不想編寫單元測試,那么在using case中包裝所有邏輯是這種情況下的最佳選擇。
using
聲明方法是您在上面提出的兩種方法中最好的。 使用這種方法,可以確保ObjectContext
在使用后關閉並處理掉。
使用您的其他方法,可以假設ObjectContext
可以保持未閉合,從而占用與數據庫的連接。 要查看此操作,請嘗試使用其他方法創建示例應用程序,然后使用EFProfiler對其進行概要分析,並觀察ObjectContext
打開的數量,同時關閉的數量將顯着減少。
我最近參與了一個項目,該項目在高使用率下遇到了數據庫問題,采用了你的第二種模式(你可以在這里看到我的問題)。 由於我沒有足夠的時間在項目/代碼庫上太大,我沒有選擇切換到using
語句方法。 相反,我采取了以下手動強制處置的ObjectContext
的End_Request
在Global.asax中(我有一個實例DbContext
我的靜態實例BusinessLayerService
:
protected void Application_EndRequest(object sender, EventArgs e)
{
BusinessLayerService.Instance.Dispose();
BusinessLayerService.Instance = null;
}
但是,如果您從項目開始有選項: 我強烈建議使用using
模式
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.