C# foreach 导致 There is has an open DataReader Associated 错误
我的 accountRepository 中有以下代码
public string[] GetRolesForUser(string email)
{
// User rolesUser = FindByMail(email);
IEnumerable<UserRole> RoleList = context.UserRolesSet.Where(u => u.user_id == 1).AsEnumerable();
string[] arr1 = new string[RoleList.Count()];
int i = 0;
foreach (UserRole r in RoleList)
{
arr1[i] = r.roles.name;
i++;
}
return arr1;
}
这应该可以工作,但不能。当它循环遍历 foreach 循环时,它会抛出以下错误:
异常详细信息:MySql.Data.MySqlClient.MySqlException:已经有一个与此连接关联的打开的 DataReader,必须先将其关闭。
我的 foreach 循环错误吗?
I have the following bits of code in my accountRepository
public string[] GetRolesForUser(string email)
{
// User rolesUser = FindByMail(email);
IEnumerable<UserRole> RoleList = context.UserRolesSet.Where(u => u.user_id == 1).AsEnumerable();
string[] arr1 = new string[RoleList.Count()];
int i = 0;
foreach (UserRole r in RoleList)
{
arr1[i] = r.roles.name;
i++;
}
return arr1;
}
This should work but it doesn't. When it looping through the foreach loop it throws me this error:
Exception Details: MySql.Data.MySqlClient.MySqlException: There is already an open DataReader associated with this Connection which must be closed first.
Is my foreach loop wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以简化该方法:
You could simplify the method:
尝试以下代码。使用 ToArray 确保它预先填充所有 UserRoles,以便使用 DataReader 完成。
Try the following code. Using ToArray makes sure it populates all of the UserRoles before hand so it'll be finished with the DataReader.