2016-10-16 4 views
1

asp.net MVCデフォルトコードのRegisterViewModelクラスに2つの新しいフィールドを追加しました。検証は機能しますが、新しく追加されたフィールドの値はデータベースに挿入されず、他のフィールドが挿入されます。ページからエラーは返されません。登録フォームに新しいプロパティを追加した後にEFがデータベースに挿入されない

私はどこか辺りで、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); 
    } 
+0

コードを共有できますか? –

+0

コンテキストオブジェクトに対して 'SaveChanges'が呼び出されていることは確かですか? – Dai

+0

私は 'AccountController'に' SaveChanges'を持っていません – hello

答えて

1

はあなたがいないのViewModel RegisterViewModelモデルApplicationUserを変更する追加する必要がデータベースに新しいフィールドを追加する必要がある場合。 RegisterViewModelモデルに新しいフィールドを追加する必要がありますが、RegisterViewModelはUIのみに使用されているため、実際にはApplicationUserクラスを更新する必要があります。たとえば、新しいフィールドを追加する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; 
     } 
    } 

を移行し、コードの保存で、次に必要な任意の検証であなたのViewModel RegisterViewModelpublic string PersonId { get; set; }を追加する必要がViewModelには

var user = new ApplicationUser 
      { 
       UserName = model.Email, 
       Email = model.Email, 
       PersonId = model.PersonId, 
      }; 
result = await UserManager.CreateAsync(user, model.Password); 
をモデルに変換します
0

ApplicationUserインスタンスに新しいプロパティを割り当てなかった、モデルクラス内に `PhoneNumber 'プロパティを追加したとします。その値を次のようにユーザにコピーする必要があります

var user = new ApplicationUser { UserName = model.Email, Email = model.Email,PhoneNumber=model.PhoneNumber }; 
関連する問題