在"Register"期间将其他配置文件数据保存在 ASP.Net 标识 (MVC) 中



我需要在用户注册期间存储额外的信息,例如:名,姓等

我的问题有两个部分:

  1. 我如何在注册时保存我的附加信息?
  2. 当前方法抛出错误:

一个或多个实体验证失败。查看'EntityValidationErrors'属性了解更多细节。我已经在VS中检查了"Watch",也使用了try-catch,但没有帮助。

提前感谢您的帮助!


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);
    }

我知道我应该把FirstNameLastName放在里面:

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

既然你的问题有两个部分:

  1. 您存储附加信息的方法是正确的
  2. 你不能继续,除非你看到实际的错误,为了看到详细信息,你需要在创建用户的地方添加这个。

    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);
        }
    }
    

相关内容

  • 没有找到相关文章

最新更新