Click here to Skip to main content
15,883,901 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I customized some functionalities of Identity system to fit my needs.

I have the following ApplicationUserManager:

C#
public class ApplicationUserManager : UserManager<ApplicationUser, long>
{
    //Constructors and other methods...

    public bool AddUserToRole(long userId, string roleName)
    {
        return this.AddToRole(userId, roleName).Succeeded;
    }

    public bool ClearAllUserRoles(long userId)
    {
        foreach (var role in this.GetRoles(userId))
        {
            if (!this.RemoveFromRole(userId, role).Succeeded)
            {
                return false;
            }
        }
        return true;
    }
}


And the other custom classes are:

C#
public class ApplicationUser : IdentityUser<long, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
    public virtual UserInfo UserInfo { get; set; }

}

public class ApplicationRole : IdentityRole<long, ApplicationUserRole>
{
    public ApplicationRole() : base() { }
    public ApplicationRole(strin//sets...tring description)
    {
        //sets...
    }
    public virtual string Description { get; set; }
}

public class ApplicationUserRole : IdentityUserRole<long> { }


Adding users and adding them to roles seems to be working fine. My problem is when I want to remove a user from roles.

When I want to Add user to a list of roles, I start clearing the user from all roles that he is already in with the method `ClearAllUserRoles(long userId)` and after I add him to each selected role.

My problem is that the `RemoveFromRole(userId, role)` method used in `ClearAllUserRoles(long userId)` only puts the fields `ApplicationUser_Id` and `ApplicationRole_Id` of my `AspNetUserRoles` table to null, leaving the fields `UserId` and `RoleId` filled so when I try to reassign the user to a role that he was already in the following exception is thrown:

{"Violation of PRIMARY KEY constraint 'PK_dbo.AspNetUserRoles'. Cannot insert duplicate key in object 'dbo.AspNetUserRoles'. The duplicate key value is (16, 1).\r\nThe statement has been terminated."}

This is my `OnModelCreating()`method:

C#
protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        EntityTypeConfiguration<ApplicationUser> table =
            modelBuilder.Entity<ApplicationUser>().ToTable("AspNetUsers");

        modelBuilder.Entity<ApplicationUser>().HasMany<ApplicationUserRole>((ApplicationUser u) => u.Roles);
        modelBuilder.Entity<ApplicationUserRole>().HasKey((ApplicationUserRole r) =>
            new { UserId = r.UserId, RoleId = r.RoleId }).ToTable("AspNetUserRoles");

        EntityTypeConfiguration<ApplicationRole> entityTypeConfiguration1 =
            modelBuilder.Entity<ApplicationRole>().ToTable("AspNetRoles");

        entityTypeConfiguration1.Property((ApplicationRole r) => r.Name).IsRequired();

    }


And in my Migration, the create table is like this:

C#
CreateTable(
            "dbo.AspNetUserRoles",
            c => new
                {
                    UserId = c.Long(nullable: false),
                    RoleId = c.Long(nullable: false),
                    ApplicationUser_Id = c.Long(),
                    ApplicationRole_Id = c.Long(),
                })
            .PrimaryKey(t => new { t.UserId, t.RoleId })
            .ForeignKey("dbo.AspNetUsers", t => t.ApplicationUser_Id)
            .ForeignKey("dbo.AspNetRoles", t => t.ApplicationRole_Id)
            .Index(t => t.ApplicationUser_Id)
            .Ind;x(t => t.ApplicationRole_Id);


My Questions are:

1. Should my `AspNetUserRoles` table have those 4 columns (`ApplicationUser_Id`, `ApplicationRole_Id`, `UserId`,`RoleId`) or I am doing something wrong in the `OnModelCreating()`method of my database context?

2. Is the `RemoveFromRole(userId, role)` method working as expected or it should delete the all row of `AspNetUserRoles` table?
Posted
Updated 20-Jul-14 4:06am
v2
Comments
Kornfeld Eliyahu Peter 20-Jul-14 9:52am    
There is too much code in this question. It's really hard to read it.
1. try to remove unnecessary code
2. format all the rest
Andre Peixoto 20-Jul-14 10:09am    
I think now is more readable. Sorry, it is my first question here in code project.
[no name] 20-Jul-14 9:58am    
How would you expect anyone to answer your "questions"?
1. What does having 4 columns have to do with doing anything wrong? If you need 4 columns then use 4 columns. If not, reduce or increase the columns per your requirement.
2. We can't possibly know what it is that you would expect.
Andre Peixoto 20-Jul-14 10:16am    
In the first question, I don't understand why columns `ApplicationUser_Id` and `ApplicationRole_Id` are created in AspNetUserRoles table so I am asking how can I change the code to be able to have just columns `UserId` and `RoleId`, which I think is sufficient.

In the second, my question is that if when we remove a user from a role the only change is the delete of the respective row in AspNetUserRoles table or if it should do somthing else...

I'm doing those questions because I'm just starting with ASP.NET Identity.
[no name] 20-Jul-14 10:34am    
For you first question, I don't understand why you would think that we would know what your requirements are for your code. If you don't want or need 4 columns in your database then don't have 4 columns. We would have no idea at all why you created 4 columns to begin with.
Same pretty much goes for your second question. If you want to delete the row, then delete the row. Again, we would have no idea at all what your requirement is.

1 solution

I'm not sure why you are not satisfied with default role provider from the ASP.NET engine (specially as you are a beginner), however if you want to control every aspect of role handling you better learn how to create your own role provider...
Start here: http://msdn.microsoft.com/en-us/library/vstudio/8fw7xh74(v=vs.100).aspx[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900