ApplicationUser and ApplicationRole navigation properties in Identity 2.0.0

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

here

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 only get RoleId

Is there a way to make a standard many-to-many mapping between ApplicationUser and ApplicationRole?

I want to do something like this

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

UPDATE:

after some work on this issue, I found a solution for my business. it may not be as elegant as it can be, but in my case I have to extend IdentityUserRole with additional navigation properties

I have expanded IdentityUserRole to ApplicationUserRole and made appropriate changes to all solutions. 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 a specific role as follows:

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

in my case AplicationUserRole is needed to store additional navigation properties so that the solution works for me. but I'm still wondering how to create a clean many-to-many relationship between IdentityUser and IdentityRole

+6
source share
1 answer

IdentityUser.Roles() provides you with a set of IdentityUserRole objects that contain only the RoleId and UserId . To get a collection of Role objects for the user, you should use the RoleManager class (typing this from the top of the head so that it doesn't 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); } } 
+2
source

Source: https://habr.com/ru/post/972449/


All Articles