views:

225

answers:

3

Hello

I have this piece of code:

    public string[] GetUsergroupRoles(string username)
    {
        var qry = from ug in _entities.Usergroups
               from r in _entities.Roles
               from u in _entities.Users
               where u.Username == username
               group r by
               new
               {
                   r.RoleID
               };

        return qry.ToArray();
    }

I get error "...Data.Models.Role>[]' to 'string[]'. An explicit conversion exists (are you missing a cast?)"

whats needed to make it return an array of strings?

/M

+3  A: 

Well, you're creating a sequence of groups (and I'm not sure why you're using an anonymous type to do so - you should be able to just use group r by r.RoleID).

What string would you expect from each group?

Jon Skeet
I'm using an anonymous type since I'm trying to assign those roles to current user logged in with formsauthentication, like this Roles.AddUserToRoles(_username, array-here)
molgan
@molgan: And why do you think that means you need an anonymous type? You've only got one value in there - why not just use `r.RoleID`? What do you believe anonymous types are doing for you?
Jon Skeet
+1  A: 

You are trying to cast a SomeType[] to a string[] and the compiler is complaining that it doesn't know how since you haven't defined a cast.

Try looping over the array and collection the specific string attribute of SomeType (or ToString() equivalent) into an array.

Gishu
A: 

Try iterating through qry and accumulate the result of ToString method of each item into a string[] variable, then returning it. Something like this:

// your code here

string[] ret = new string[qry.Length];
int i = 0;
foreach (var item in qry) {
  ret[i] = qry.ToString()
  i++;
}
return ret;
Doug
Arrays don't have an Add method like a list ; Also you seem to be calling String.Add (typo?)
Gishu
Yes, the code had errors. I think now it's right.
Doug