将新属性添加到注册表单后,EF不会插入数据库

时间:2016-10-16 01:42:46

标签: c# asp.net entity-framework

我在asp.net MVC默认代码中向RegisterViewModel类添加了两个新字段。验证有效,但新添加的字段的值不会插入数据库,而是插入其他字段。页面不会返回任何错误。

我猜我需要在AccountController课内做一些事情,在这附近:

var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);

不确定如何。

    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
               //await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
                 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>");

                TempData["Email"] = user.Email;
                return RedirectToAction("Confirm", "Account");
            }
            AddErrors(result);
        }
        // If we got this far, something failed, redisplay form
        return View(model);
    }

2 个答案:

答案 0 :(得分:1)

如果您需要向数据库添加新字段,则需要添加以修改模型ApplicationUser而不是viewModel RegisterViewModel。 因此,在您的问题中,您需要向RegisterViewModel模型添加新字段,但实际上您需要更新ApplicationUser类,因为RegisterViewModel仅用于UI。例如,要添加新字段PersonId,您需要修改ApplicationUser模型并迁移数据库

public class ApplicationUser : IdentityUser
    {
    public string PersonId { get; set; }
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

并使用您需要的任何验证将public string PersonId { get; set; }添加到您的ViewModel RegisterViewModel,然后在保存代码中将ViewModel转换为模型

var user = new ApplicationUser 
            {
                UserName = model.Email,
                Email = model.Email,
                PersonId = model.PersonId,
            };
result = await UserManager.CreateAsync(user, model.Password);

答案 1 :(得分:0)

您没有在ApplicationUser实例中分配新属性,假设您在模型类中添加了“PhoneNumber”属性,那么您必须将其值复制到用户,如下所示

var user = new ApplicationUser { UserName = model.Email, Email = model.Email,PhoneNumber=model.PhoneNumber };
相关问题