ASP.NET username change

后端 未结 1 1889
[愿得一人]
[愿得一人] 2020-12-30 01:16

I have an asp.net site which uses the ASP.net Membership provider. Each comment, entry etc in the DB is tracked by the userID.

Since MS doesn\'t provide a way to ch

相关标签:
1条回答
  • 2020-12-30 01:56

    cptScarlet's link was good, however I despise using stored procedures if I don't have to and I favor Entity Framework whenever possible. Here's what I did to change the user name, using EF 4.0 and .NET 4.0:

    1. Right click project -> Add New Item -> ADO.NET Entity Data Model
    2. Give it a proper name, I chose "MembershipModel.edmx" and click Add
    3. Select Generate from database and click Next
    4. Add the connection to your 'aspnetdb' database (the ASP.NET membership database)
    5. Give it a proper name, I chose "MembershipEntities"
    6. Click Next
    7. Drill into Tables and select aspnet_Users
    8. Change the Model Namespace to MembershipModel
    9. Click Finish

    Now you can add code to create the EF object context and modify the database:

    public void ChangeUserName(string currentUserName, string newUserName)
    {
        using (var context = new MembershipEntities())
        {
            // Get the membership record from the database
            var currentUserNameLowered = currentUserName.ToLower();
            var membershipUser = context.aspnet_Users
                .Where(u => u.LoweredUserName == currentUserNameLowered)
                .FirstOrDefault();
    
            if (membershipUser != null)
            {
                // Ensure that the new user name is not already being used
                string newUserNameLowered = newUserName.ToLower();
                if (!context.aspnet_Users.Any(u => u.LoweredUserName == newUserNameLowered))
                {
                    membershipUser.UserName = newUserName;
                    membershipUser.LoweredUserName = newUserNameLowered;
                    context.SaveChanges();
                }
            }
        }
    }
    

    Note: I did not account for application ID's in my code. I typically only ever have one application using the ASP.NET membership database, so if you have multiple apps, you'll need to account for that.

    0 讨论(0)
提交回复
热议问题