EF Core中DbContext可以被Dispose多次


我們知道,在EF Core中DbContext用完后要記得調用Dispose方法釋放資源。但是其實DbContext可以多次調用Dispose方法,雖然只有第一次Dispose會起作用,但是DbContext多次調用Dispose方法並不會報錯。

 

我們看看下面的示例代碼,可以看到我們調用了DbContext.Dispose三次,加上using代碼塊一共四次,但是代碼並不會報錯:

string connectionString = "Server=localhost;User Id=sa;Password=1qaz!QAZ;Database=Demo";
using (var dbContext = new MyDbContext(connectionString))//MyDbContext繼承自Microsoft.EntityFrameworkCore.DbContext
{
    List<Language> languages = dbContext.Language.ToList();//通過DbContext從數據庫中查詢Language實體(表)的數據

    //多次調用DbContext.Dispose方法不會報錯
    dbContext.Dispose();
    dbContext.Dispose();
    dbContext.Dispose();
}

 

但是記住當DbContext調用Dispose方法后,就不能再用DbContext去數據庫操作數據了,除非重新new一個DbContext。

例如下面的代碼:

string connectionString = "Server=localhost;User Id=sa;Password=1qaz!QAZ;Database=Demo";
using (var dbContext = new MyDbContext(connectionString))//MyDbContext繼承自Microsoft.EntityFrameworkCore.DbContext
{
    List<Language> languages = dbContext.Language.ToList();//通過DbContext從數據庫中查詢Language實體(表)的數據

    dbContext.Dispose();//調用DbContext.Dispose方法
 List<Language> otherLanguages = dbContext.Language.ToList();//再次通過DbContext從數據庫中查詢Language實體(表)的數據,這次會拋出異常因為DbContext在上面已經被Dispose了
}

第二次調用dbContext.Language.ToList()去數據庫查詢數據給otherLanguages賦值的時候,會拋出異常,因為之前已經調用了DbContext.Dispose方法,DbContext已經不可用了,異常信息如下:

System.ObjectDisposedException: 'Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.'

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM