Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ApplicationUser and ApplicationRole navigation properties in Identity 2.0.0

in Identity 2.0.0 we have Roles navigation property in ApplicationUser with type IdentityUserRoles and we have Users navigation property in IdentityRole with same type IdentityUserRoles

here it is

namespace Microsoft.AspNet.Identity.EntityFramework
{
    // Summary:
    //     EntityType that represents a user belonging to a role
    //
    // Type parameters:
    //   TKey:
    public class IdentityUserRole<TKey>
    {
        public IdentityUserRole();

        // Summary:
        //     RoleId for the role
        public virtual TKey RoleId { get; set; }
        //
        // Summary:
        //     UserId for the user that is in the role
        public virtual TKey UserId { get; set; }
    }
}

so, when i iterate through context.Users i can get only RoleId

is there a way to make standart many-to-many mapping between ApplicationUser and ApplicationRole ?

i want to be able doing something like this

foreach (var user in ApplicationDbContextInstance.Users)
{
    List<ApplicationRole> UserRoles = user.Roles.ToList();
    /*
    some logic ... 
    */ 
}

UPDATE:

after some work on this question i have found a solution for my case. maybe its not so elegant as it can be, but in my case i have to extend IdentityUserRole with additional navigation properties

i have extended IdentityUserRole to ApplicationUserRole and make appropriate changes in all solution. here is my new IdentityUserRole:

public class ApplicationUserRole : IdentityUserRole<string>
{
    public virtual ApplicationUser User { get; set; }
    public virtual ApplicationRole Role { get; set; }
    public virtual ICollection<GeoSectorForUser> GeoSectors { get; set; }
}

and now i can get all users in certain role like this:

foreach(ApplicationRole role in db.Roles){
    List<ApplicationUser> users = role.Users.Select(s => s.User).ToList();
}

in my case AplicationUserRole is needed for storing additional navigation properties so that solution is worked for me. but i still wondering how to create clean many-to-many relation between IdentityUser and IdentityRole

like image 801
taburetkin Avatar asked Jul 18 '14 10:07

taburetkin


1 Answers

IdentityUser.Roles() gives you a collection of IdentityUserRole objects which contain only RoleId and UserId properties. To get a collection of the Role objects for a user, you should use the RoleManager class (typing this off the top of my head so may not work 100%):

var roleManager = new RoleManager();

foreach (var user in ApplicationDbContextInstance.Users)
{
    List<IdentityUserRole> UserRoles = user.Roles.ToList();

    foreach(var userRole in UserRoles)
    {
        var role = roleManager.FindbyId(userRole.RoleId);
    }

}
like image 65
DavidG Avatar answered Oct 16 '22 06:10

DavidG