Search code examples
c#asp.netsqlmembershipprovider

Displaying Member info including Roles using Sql Membership Provider


I wish to create a summary table of all users with the database tables setup according to SqlMembershipProvider schema. So far, I have:

<asp:GridView ID="UserAccounts" runat="server" AutoGenerateColumns="False">
    <Columns>
        <asp:BoundField DataField="UserName" HeaderText="UserName" />
        <asp:BoundField DataField="Email" HeaderText="Email" />
        <asp:TemplateField HeaderText="Role">
            <ItemTemplate>
                <asp:TextBox ID="RoleText" ReadOnly="true" runat="server">
                </asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

for the table, and codebehind:

UserAccounts.DataSource = Membership.GetAllUsers();
UserAccounts.DataBind();

To generate the list of users. However, as those of you who are familiar with SQLmembershipprovider, the roles associated with users are housed in multiple separate tables. Therefore, I'm not sure how to retrieve that information and have it display beside each user.

The solution I am currently thinking of is to somehow traverse the table row by row and then calling Roles.GetRolesForUser() on that username to retrieve the information and then binding that to the table. However, I'm not sure of exactly how to do this and if it's even the most efficient method.


Solution

  • Try binding to

        var userRoles = from MembershipUser user in Membership.GetAllUsers()
                        from role in Roles.GetRolesForUser(user.UserName)
                        select new { 
                            UserName = user.UserName, Email = user.Email, Role = role };
    

    or

        var userRoles = from MembershipUser user in Membership.GetAllUsers()
                        let roles = Roles.GetRolesForUser(user.UserName)
                        select new {
                            UserName = user.UserName, 
                            Email = user.Email,
                            Roles = string.Join(", ",  roles) };