hello hello - 1 month ago 7
ASP.NET (C#) Question

EF not inserting into database after adding new Properties to Registration form

I added two new fields to

RegisterViewModel
class in asp.net MVC default code. Validation works but, values for the newly added fields are not inserted into the database, other fields are inserted. No error is returned from the page.

I'm guessing I need to do some things inside
AccountController
class, somewhere around here:

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


Not sure exactly how.

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

Answer

If you need to add new field to database you need to add to modify model ApplicationUser not viewModel RegisterViewModel. So in your question you need to add new field to RegisterViewModel model but actually you need to update the ApplicationUser class because RegisterViewModel used for UI only. For example, to add new field PersonId you need to modify your ApplicationUser model and migrate your database

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

and add public string PersonId { get; set; } to your ViewModel RegisterViewModel with any Validation you need then in save code convert ViewModel to Model

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