This MySqlConnectioin is already in Use异常处理

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及时执行,然后利用执行后的结果再进行其他查询。

posted @ 2022-09-25 08:31  xsz1234  阅读(1253)  评论(0编辑  收藏  举报