C# foreach 导致 There is has an open DataReader Associated 错误

发布于 2024-11-18 20:42:17 字数 632 浏览 3 评论 0原文

我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我也只是我 2024-11-25 20:42:17

您可以简化该方法:

IEnumerable<UserRole> RoleList = context.UserRolesSet.Where(u => u.user_id == 1);

return RoleList.Select(x => x.roles.name).ToArray();

You could simplify the method:

IEnumerable<UserRole> RoleList = context.UserRolesSet.Where(u => u.user_id == 1);

return RoleList.Select(x => x.roles.name).ToArray();
困倦 2024-11-25 20:42:17

尝试以下代码。使用 ToArray 确保它预先填充所有 UserRoles,以便使用 DataReader 完成。

public string[] GetRolesForUser(string email)
{
    // User rolesUser = FindByMail(email);
    IEnumerable<UserRole> RoleList = context.UserRolesSet.Where(u => u.user_id == 1).ToArray();
    string[] arr1 = new string[RoleList.Count()];
    int i = 0;
    foreach (UserRole r in RoleList)
    {
        arr1[i] = r.roles.name;
        i++;
    }
    return arr1;
}

Try the following code. Using ToArray makes sure it populates all of the UserRoles before hand so it'll be finished with the DataReader.

public string[] GetRolesForUser(string email)
{
    // User rolesUser = FindByMail(email);
    IEnumerable<UserRole> RoleList = context.UserRolesSet.Where(u => u.user_id == 1).ToArray();
    string[] arr1 = new string[RoleList.Count()];
    int i = 0;
    foreach (UserRole r in RoleList)
    {
        arr1[i] = r.roles.name;
        i++;
    }
    return arr1;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文