开发者

C# foreach leads to There is already an open DataReader associated error

开发者 https://www.devze.com 2023-03-18 04:41 出处:网络
I have the following bits of code in my accountRepository public string[] GetRolesForUser(string email)

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?


You could simplify the method:

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

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


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消