我的测试要求删除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");
}
答案 0 :(得分: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);
}
答案 1 :(得分:0)
在SQL Server和MySQL中,您可以运行:
TRUNCATE my_aspnet_users
TRUNCATE my_aspnet_membership
TRUNCATE my_aspnet_profiles
TRUNCATE my_aspnet_roles
答案 2 :(得分:0)
如果你想删除所有成员,删除表并重新创建它,它更像是一个技巧而不是一个答案。或者使用实体框架更容易。
答案 3 :(得分: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);
}