开发者

EF - Navigation property explanation

开发者 https://www.devze.com 2023-02-07 17:17 出处:网络
I use EF 4 and Membership Provider Shipped with ASP.Net 4.0. I need find all Users in a Specific Role and Populate a DropDownList using List<ListItem>.

I use EF 4 and Membership Provider Shipped with ASP.Net 4.0.

I need find all Users in a Specific Role and Populate a DropDownList using List<ListItem>.

DataBase Tables involved are:

aspnet_Roles
aspnet_Users
aspnet_UsersInRoles

Navigation Property from aspnet_Users to aspnet_Roles (using junction table aspnet_UsersInRoles) is:

myUser.aspnet_Roles

Matching RoleID (Guid) "CE44ED48-E9F9-49C6-9E15-E40EEFDC7479")

My Script:

        using (CmsConnectionStringEntityDataModel context = new CmsConnectionStringEntityDataMod开发者_开发知识库el())
        {
            IQueryable<aspnet_Users> userQuery = from aspnet_Users in context.aspnet_Users select aspnet_Users;
            IQueryable<aspnet_Roles> roleQuery = from aspnet_Roles in context.aspnet_Roles select aspnet_Roles;
            List<ListItem> myListUsersInRoles = new List<ListItem>();
            foreach (aspnet_Users myUser in userQuery)
            {
            // PROBLEM HERE
            if (myUser.aspnet_Roles.ToString() == "CE44ED48-E9F9-49C6-9E15-E40EEFDC7479")
                myListUsersInRoles.Add(new ListItem(myUser.UserName.ToString(), myUser.UserId.ToString()));

            uxListUsers.DataSource = myListUsersInRoles;
            uxListUsers.DataBind();
        }`

Problems: IF return FALSE always, so I am not able to populate List<>. I suppose I am doing wrong in if an some Properties.

Do you have any ideas? Thanks for your time.


myUser.aspnet_Roles is an EntitySet<aspnet_Roles> (in other words, a collection of roles, so it's highly unlikely that it's string representation happens to match the string representation of the role you're after's ID.

There are several ways you could fix it. One is:

// ...
if (myUser.aspnet_Roles.Any(r => r.RoleId.ToString() == "CE44ED48-E9F9-49C6-9E15-E40EEFDC7479"))
// ...

Also note that from y in x select y is just the same as x, so you could write

foreach (aspnet_User myUser in context.aspnet_Users)
// ...

And not bother declaring userQuery or roleQuery. (You don't actually seem to be using roleQuery anywhere anyway...)

Also, you could look at using the membership/roles API to fetch users in a role:

using System.Web.Security; // at the top of your file
var usersInRole = Roles.GetUsersInRole("name of role here, NOT the guid");

Note that this returns an array of usernames, not user objects, so you'd have to do a little extra work to get the User ID, but it is something you could think about...

0

精彩评论

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

关注公众号