Casting EF class collection to string array

Casting EF class collection to string array

Old forum URL: forums.lhotka.net/forums/t/10749.aspx


Helio posted on Friday, October 07, 2011

I have a data transfer object defined as:

  public class UserDto
  {
    public string UserId { get; set; }
    public string[] Roles { get; set; }
  }

My database has the following tables:

User: UserId, UserName, Password

Role: RoleId, RoleName

UserRole: (many to many) contains UserId, RoleId.


In my code I want to populate the the UserDto object using a Linq to Entity Framework as shown below:

         public UserDto Fetch(string userId, string password)
        {
            using (var ctx = ObjectContextManager<CharisCTKEntities>.GetManager("CharisCTKEntities"))
            {
                var result = (from r in ctx.ObjectContext.Users
                              where r.UserId == userId && r.Password == password
                              select new UserDto
                              {
                                  UserId = r.UserId,
                                  Roles = r.UserRoles
                              }
                              ).FirstOrDefault();
               
                if (result == null)
                    throw new DataNotFoundException("User");
                return result;
            }
        }


However I am having problem casting r.UserRoles to UserDto.Roles. I've tried Roles = r.UserRoles.ToArray() but no good.

The error is:
Error 1 Cannot implicitly convert type 'System.Data.Objects.DataClasses.EntityCollection<CC.CharisCTK.DalEf.UserRole>' to 'string[]
Any help on how to do this casting would be greatly appreciated.
Thank you

Copyright (c) Marimer LLC