How to remove a user with a role in ASP.NET MVC4 SimpleMembership?

Thanks for watching.

Background

In my current project, the client would like me to use ASP.NET MVC4 Simple membership. Usually I do not use .NET membership classes, so maybe I am missing something simple, but I can’t delete the user through the code, because there is a foreign key constraint between the webpages_UsersInRoles table and the UserProfile table.

I tried using Membership.DeleteUser(id, true); , since setting "true" should cascade the deletion, but even this fails if there is a role assigned to the user.

I tried to enter the mdb file through the server explorer and set the delete action in FK to CASCADE , but the option for the delete action is disabled.

As a last effort, I created a separate entity class (.edmx) from the membership database in the hope that I can hack my way to successful deletion using C #, but the .edmx generation refuses to populate the webpages_UsersInRoles table!

I am using C #, .NET 4.5.

Question

Using C #. How to remove a user from MVC4 SimpleMembership if one or more roles have been assigned to this user?

+4
source share
2 answers

I cannot find so quickly why the UserInRoles table does not have an exception rule in the delete cascade when the user is deleted, but maybe this answer helps:

 void DeleteUserRoles(string username) { foreach (var role in Roles.GetRolesForUser(username)) Roles.RemoveUserFromRole(username, role); } 
+7
source

Optionally use RemoveUserFromRoles (plural)

 void DeleteUserRoles(string username) { Roles.RemoveUserFromRoles(username, Roles.GetRolesForUser(username)); } 
0
source

All Articles