0

我有一个测试要求删除 SimpleMembershipProvider UserProfile 表中的所有用户。我想在我的 SeedMembership() 方法中执行此操作(如下)。像membership.DeleteAllUsers 这样的东西。知道如何做到这一点吗?

private int SeedMembership()
        {

            if (!WebMatrix.WebData.WebSecurity.Initialized)
            {
                WebSecurity.InitializeDatabaseConnection("TestConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
            }


            var roles = (SimpleRoleProvider)Roles.Provider;
            var membership = (SimpleMembershipProvider)Membership.Provider;

            if (!roles.RoleExists("Admin"))
            {
                roles.CreateRole("Admin");
            }
            if (!roles.RoleExists("User"))
            {
                roles.CreateRole("User");
            }

            // Somehow delete all users here

            if (membership.GetUser("user", false) == null)
            {
                membership.CreateUserAndAccount("user", "covert");
            }
            if (!roles.GetRolesForUser("user").Contains("Admin"))
            {
                roles.AddUsersToRoles(new[] { "user" }, new[] { "admin" });
            }

            return membership.GetUserId("user");

        }
4

4 回答 4

1

在 SQL Server 和 MySQL 中,您可以运行:

TRUNCATE my_aspnet_users
TRUNCATE my_aspnet_membership
TRUNCATE my_aspnet_profiles
TRUNCATE my_aspnet_roles
于 2013-05-05T19:05:38.660 回答
1

通过这个链接

http://blogs.thesitedoctor.co.uk/tim/Trackback.aspx?guid=b16a67b9-4c34-4566-a689-088e6c087405

或者干脆这样做......

foreach (MembershipUser u in Membership.GetAllUsers())
{
 Membership.DeleteUser(u.UserName, true);
}
于 2013-05-05T18:55:57.307 回答
0

好吧,如果您想删除所有成员,请删除表并重新创建它,这更像是一个技巧而不是答案。或者使用实体框架更容易。

于 2013-05-05T19:10:36.447 回答
0

我不得不在几个项目上实现类似的功能,我发现最简单的方法是这样(从记忆中,但我认为这会起作用):

var dbUsernames = context.Database.SqlQuery<string>("SELECT UserName FROM UserProfile");
foreach (string dbUsername in dbUsernames)
{
    string[] userRoles = Roles.GetRolesForUser(dbUsername);
    if (userRoles != null && userRoles.Length > 0)
    {
        Roles.RemoveUserFromRoles(dbUsername, userRoles); 
    }
    int userId = context.Database.SqlQuery<int>("SELECT UserId FROM UserProfile WHERE UserName = {0}", dbUsername).First();
    // HERE: Delete any other dependent rows in other tables that use UserId, and have referential integrity
    // Now tear down any final bits and delete the user, for example: 
    Membership.DeleteUser(dbUsername, true);
    context.Database.ExecuteSqlCommand(
        "DELETE FROM webpages_Membership WHERE UserId = {0}", userId);
}
于 2013-05-13T10:01:37.937 回答