views:

93

answers:

2

Hi, I have a database containing users and roles. The table Users has a reference to the table roles as each user is bind to a role (one and only one). When I use linq to retrieve the users, the field "role" shows in a datagrid as an integer (which is the primary key of the table Roles). However, I'd like to replace the field Role of the user for the actual Name field of the Role table. Any idea on how to do it?

The code of the datacontext now is the default one, what linq query should I use to get what I need?

public IQueryable<Usuarios> GetUsuarios()
{
        return this.ObjectContext.Usuarios;
}
A: 

Do this to early bound the Roles to the Users:

return this.ObjectContext.Usuarios.Include("Roles");
alexs
+1  A: 

The canonical way to do this would be to have a view-specific model for your datagrid and use LINQ to select into that view-specific model. My example assumes LINQ to SQL.

public IEnumerable<UserWithRoles> GetUsersWithRoles()
{
     return this.ObjectContext
                .Users
                .Select( u => new UserWithRole { Name = u.Name, ..., Role = u.Roles.First().Name } );
}
tvanfosson
Just another question related to this. If I use this solution, can I still be using the master/detail funcionality? I mean, if I use the SelectedItem on the Grid to set the Detail controls, will it use the User or the UserWithRoles? And if it's the latter, how can I get back to the original User?Thanks!
brafales
I think you just need to identitfy the correct method on your data source that would return a detail specific view model (or the actual business object if they are the same). Note that you'd need to include the ID (presumably) in your master view model that would correspond to the correct details item to retrieve.
tvanfosson