Save additional profile data during “Register” in

2019-03-07 01:54发布

问题:

I need to store additional information during user registration such as: First Name, Last Name and etc.

My question has two parts:

  1. How can I save my additional information during Register?
  2. My current method throws error:

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. I have already checked "Watch" inside VS and also used try-catch but it didn't help.

Thanks in advance for your help!


IdentityModels.cs

public class ApplicationIdentityAccount : IdentityUser
{
  public virtual ICollection<AccountProfile> AccountProfiles { get; set; }
}


public class AccountProfile
{


      [Key]
      public string AccountProfileID { get; set; }


      [DisplayName("First Name")]
      [StringLength(50)]
      [Required(ErrorMessage = "First name is required")]
      public string FirstName { get; set; }


      [DisplayName("Middle Name")]
      [StringLength(50)]
      public string MiddleName { get; set; }


      [DisplayName("Last Name")]
      [StringLength(50)]
      [Required(ErrorMessage = "Last name is required")]
      public string LastName { get; set; }

      public string UserId { get; set; }
      [ForeignKey("UserId")]
      public virtual ApplicationIdentityAccount User { get; set; }

}


public class ApplicationIdentityDbContext : IdentityDbContext<ApplicationIdentityAccount>
  {
 public ApplicationIdentityDbContext()
 : base("ApplicationIdentity", throwIfV1Schema: false)
  {
  }


    public static ApplicationIdentityDbContext Create()
      {
      return new ApplicationIdentityDbContext();
      }



public System.Data.Entity.DbSet<AccountProfile> AccountProfile { get; set; }

 }

AccountViewModels.cs > RegisterViewModel

 public class RegisterViewModel
    {

    [Required]
    [Display(Name = "Username")]
    public string UserName { get; set; }

    [Required]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [Required]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

AccountController.cs

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
      {
         if (ModelState.IsValid)
              {
               var user = new ApplicationIdentityAccount
                {
                   UserName = model.UserName,
                   Email = model.Email,
                   AccountProfile = new[] {new AccountProfile()
                {
                    FirstName = model.FirstName,
                    LastName = model.LastName
                }}
                };

             var result = await UserManager.CreateAsync(user, model.Password);


             if (result.Succeeded)
                {

               await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                        // Send an email with this link
                        // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                        // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                        // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                        return RedirectToAction("Index", "Home");
                    }
                    AddErrors(result);
                    }


                // If we got this far, something failed, redisplay form
                return View(model);
    }

I know that I should place FirstName and LastName inside:

var user = new ApplicationIdentityAccount
                    {
                       UserName = model.UserName,
                       Email = model.Email,
                    };

回答1:

Since your question has two parts:

  1. Your method for storing additional information is correct
  2. You can't proceed unless you see the actual error, in order to see the details you need to add this where you create the user.

    public override int SaveChanges()
    {
        try
        {
            return base.SaveChanges();
        }
        catch (DbEntityValidationException ex)
        {
            // Retrieve the error messages as a list of strings.
            var errorMessages = ex.EntityValidationErrors
                    .SelectMany(x => x.ValidationErrors)
                    .Select(x => x.ErrorMessage);
    
            // Join the list to a single string.
            var fullErrorMessage = string.Join("; ", errorMessages);
    
            // Combine the original exception message with the new one.
            var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
    
            // Throw a new DbEntityValidationException with the improved exception message.
            throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
        }
    }