Mark
Mark

Reputation: 7818

How do I stop this error when creating a new Role Provider?

I'm trying to add a new Role Provider into my MVC5 project - however on the "return roles.ToArray();" line I get the error:

Cannot implicitly convert type 'wb.Models.UserRole[]' to 'string[]'

    public override string[] GetRolesForUser(string username)
    {
        var roles = db.UserRole
                    .Where(x => x.UserName
                    .Equals(username, StringComparison.CurrentCultureIgnoreCase));

        if (roles != null)
                return roles.ToArray();
            else
               return new string[] { }; ;
     }

Can anyone suggest how I correct this please?

Upvotes: 0

Views: 35

Answers (2)

Christos
Christos

Reputation: 53958

The problem in your code is in the following line:

roles.ToArray();

This returns an array of wb.Models.UserRole instead of an array of strings, string[]. One option I see, it would be before the call of ToArray() to select an anonymous type with one string property, which would contain the information you want. Something like this:

 var roles = db.UserRole
               .Where(x => x.UserName
               .Equals(username, StringComparison.CurrentCultureIgnoreCase))
               .Select(x => x.RoleName);

I am not sure if your class has a property called RoleName, but in general terms you should project the results of your query like above, in a sequence of strings. Then calling ToArray will create an array of strings and you would be more than done.

Upvotes: 1

David L
David L

Reputation: 33833

You are returning an array of roles, not role names. Select out the names and return them as an array.

public override string[] GetRolesForUser(string username)
{
    var roleNames = 
        db.UserRole
            .Where(x => x.UserName.Equals(username, 
                StringComparison.CurrentCultureIgnoreCase))
            .Select(x => x.RoleName);

    if (roleNames.Count() > 0)
        return roleNames.ToArray();
    else
        return new string[] { }; ;
 }

Upvotes: 2

Related Questions