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.'

 

转载于:https://www.cnblogs.com/OpenCoder/p/10320070.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值