开发者

Linq replace field for a subquery

I have a database containing users and roles. The table Users has a reference to the table roles as each user is bin开发者_高级运维d 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;
}


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


Do this to early bound the Roles to the Users:

return this.ObjectContext.Usuarios.Include("Roles");
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜