8

我很确定我已经遵循了所有步骤,但似乎遗漏了一些东西。在 MVC4 应用程序中使用 simplemembership。将电子邮件添加到 UserProfile 表并在 Register 和 UserProfile 模型中,将其添加到 Register 方法中,但仍然出现错误。这是一些代码:

楷模:

public class UserProfile
{
    public int UserId { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
}

public class RegisterModel
{
    [Display(Name = "Email Address")]
    [StringLength(20)]
    // [Required]
    public string Email { get; set; }

    [Display(Name = "Date of Birth")]
    //   [Required]
    public DateTime DOB { get; set; }

    [Required]
    [System.Web.Mvc.Remote("VerifyUserExists", "Account", ErrorMessage="That Username is already taken.")]
    [Display(Name = "User name")]
    public string UserName { 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; }
}

控制器:

    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            try
            {
                WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Email = model.Email });
                WebSecurity.Login(model.UserName, model.Password);

                return RedirectToAction("Index", "Home");
            }
            catch (MembershipCreateUserException e)
            {
                ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
            }


        }

我没有尝试使用电子邮件地址作为登录名,只是想在注册步骤中获取它,以便发送自动确认电子邮件。

我已经尝试过使用 EF 模型中包含的 UserProfile 表,并且没有任何区别。我已经确认数据库中的表有一个电子邮件列。

4

2 回答 2

0

如果您使用默认连接,请单击查看 -> 服务器资源管理器打开数据库,然后展开默认连接。在 Tables 下,您将看到 UserProfile 表。首先将列添加到表中并更新数据库,然后将额外的字段添加到类中。

于 2013-09-23T09:38:50.690 回答
0

我猜测 Email 属性(在您的 UserProfile 类中)是您在第一次执行应用程序后添加的东西,所以如果在您更改模型并添加 Email 属性之前该表已经存在,它可能是异常的原因。

正如您在其中一条评论中提到的那样:

如果我从控制器的 Register 方法中删除部分 new{ Email etc ',它会通过

要解决这个问题,我认为您需要在 DbContext 派生类中执行类似的操作。(假设您使用代码优先方法):

     public class myDbContext: DbContext
{
    public myDbContext()
        : base("DefaultConnection")
    {
        Database.SetInitializer<myDbContext>(new DropCreateDatabaseIfModelChanges<myDbContext>());
    }

    public DbSet<UserProfile> UserProfiles { get; set; }

}

默认设置是CreateDatabaseIfNotExists,所以如果您的 UserProfile 表已经存在,它不会再次创建它并且没有找到您的新 Email 属性(它在您的模型中但不在数据库表中);

于 2013-12-20T12:02:45.113 回答