How to I add more custom fields using custom membership in mvc?

Neo picture Neo · Jan 6, 2012 · Viewed 9.5k times · Source

I have overridden the membership methods to create a custom membership.

In the account model I've overridden the method CreateUser:

public override MembershipUser CreateUser(string username, string password,
    string email, string passwordQuestion, string passwordAnswer,
    bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
    ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(
        username, password, true);
    OnValidatingPassword(args);

    if (args.Cancel)
    {
        status = MembershipCreateStatus.InvalidPassword;
        return null;
    }

    if (RequiresUniqueEmail && GetUserNameByEmail(email) != "")
    {
        status = MembershipCreateStatus.DuplicateEmail;
        return null;
    }

    MembershipUser u = GetUser(username, false);
    if (u == null)
    {
        UserRepository _user = new UserRepository();

        // Here I call my new method which has fields I've created in the
        // User table; I'm using entity framework.    
        _user.CreateUser(username, password, email);
        status = MembershipCreateStatus.Success;
        return GetUser(username, false);
    }
    else
    {
        status = MembershipCreateStatus.DuplicateUserName;
    }

    return null;
}

public MembershipUser CreateUser(string username, string password,
    string email)
{
    using (CustomMembershipDB db = new CustomMembershipDB())
    {
        User user = new User();
        user.UserName = username;
        user.Email = email;
        user.PasswordSalt = CreateSalt();
        user.Password = CreatePasswordHash(password, user.PasswordSalt);
        user.CreatedDate = DateTime.Now;
        user.IsActivated = false;
        user.IsLockedOut = false;
        user.LastLockedOutDate = DateTime.Now;
        user.LastLoginDate = DateTime.Now;

        //Generate an email key
        // user.NewEmailKey = GenerateKey();

        db.AddToUsers(user);
        db.SaveChanges();

        //send mail
        // SendMail(user);

        return GetUser(username);
    }
}

Now here I need to add more two fields like first name and last name but how can I pass it to the above method?

As the override method CreateUser will give me an error if I add parameters like firstname and last name into it :(

Answer

Qorbani picture Qorbani · Jan 6, 2012

You need to implement Custom Membership User. Here is a sample implementation:

Also take a look at this thread: