首页 > 数据库 >This MySqlConnectioin is already in Use异常处理

This MySqlConnectioin is already in Use异常处理

时间:2022-09-25 08:44:57浏览次数:87  
标签:Use already MySqlConnectioin 查询 mysql using

This MySqlConnectioin is already in Use异常处理记录

今天使用EF Core和Mysql的时候,遇到了一个问题,具体描述如下:
Nuget安装了Pomelo.EntityFrameworkCore.MySql,然后在同一个using(var context=new MyDbContext())作用域中,
先是查询了一组对象,涉及LazyLoad,然后在foreach迭代中继续利用查出来的属性再次查询该组对象,于是报错This MySqlConnectioin is already in Use,按照错误提示搜索了一下,
发现有人之前已经遇到过类似问题了,
https://www.cnblogs.com/ricolee/p/This-MySqlConnection-is-already-in-use.html
https://stackoverflow.com/questions/65771757/exception-this-mysqlconnection-is-already-in-use-when-using-mysql-server-ho/67601933#67601933
大概意思就是mysql provider对lazyloading的实现方式导致读期间不能进行数据库操作,涉及connection占用。

之后我继续测试了sqlserver类似问题,也存在There is already an open DataReader associated with this Connection which must be closed first
这个错误描述就很清楚了,是因为延迟查询使用的是DataReader,占用了Connection了。
所以以后EF不能使用此类写法,
正确处理是,使用ToList()让lazyloading及时执行,然后利用执行后的结果再进行其他查询。

标签:Use,already,MySqlConnectioin,查询,mysql,using
From: https://www.cnblogs.com/newlifechou/p/16727211.html

相关文章