2017-05-05 74 views
0

工作站安裝:添加列AspNetUsers表

  • 的Windows 8.1專業版
  • 的Visual Studio Pro的2013 v 12.0.40629.00更新5
  • 淨v 4.6.01055

背景:

我使用個人帳戶身份驗證創建了我的項目,然後按照我在Youtube上找到的指南創建了一個來自現有數據庫的EDMX數據模型。我這樣做了爲我的網站創建身份驗證。然後,我修改了web.config文件中的默認連接以指向我現有的數據庫。當我在修改默認連接後註冊第一個用戶帳戶時,它會自動生成我現有數據庫中所有必需的AspNet表。

問題:

我需要一個自定義的列添加到AspNetUsers表。我遵循微軟的指南,發現here,但是當我到了關於修改Models \ IdentityModels.cs文件的步驟時,我無法這樣做,因爲文件丟失了。

試圖解析:

我已經嘗試通過簡單地添加列到SQL數據庫自己,然後編輯我的WebAPI代碼繞過這一點。

首先我編輯了AccountBindingModels.cs文件中的RegisterBindingModel類。我添加了PeopleID部分。

public class RegisterBindingModel 
{ 
    [Required] 
    [Display(Name = "User name")] 
    public string UserName { get; set; } 

    [Required] 
    [Display(Name = "Email")] 
    public string Email { get; set; } 

    [Required] 
    [Display(Name = "PeopleID")] 
    public string PeopleID { 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文件中找到的Register類。我添加了與PeopleID有關的行。

[AllowAnonymous] 
    [Route("Register")] 
    public async Task<IHttpActionResult> Register(RegisterBindingModel model) 
    { 
     if (!ModelState.IsValid) 
     { 
      return BadRequest(ModelState); 
     } 

     IdentityUser user = new IdentityUser 
     { 
      UserName = model.UserName, 
      Email = model.Email, 
      PeopleID = model.PeopleID, 
     }; 

     IdentityResult result = await UserManager.CreateAsync(user, model.Password); 
     IHttpActionResult errorResult = GetErrorResult(result); 

     if (errorResult != null) 
     { 
      return errorResult; 
     } 

     return Ok(); 
    } 

現在,一旦我添加了PeopleID = model.PeopleID,線我得到這一條錯誤消息「Microsoft.AspNet.Identity.EntityFramework.IdentityUser」不包含定義‘的peopleid’」。當我到IdentityUser.cs文件時,它被鎖定,並且不允許我編輯它。

回答

1

該錯誤表示您未將該列添加到模型(edmx)中的IdentityUser類/表中。

問題是,您通常不能只擴展IdentityUser,您需要繼承IdentityUser。通常,因爲你的情況我懷疑AspNetUsers表是edmx的一部分。所以我想你可以在那裏添加一列來解決這個問題。但我不確定。

在代碼優先的情況下(如Microsoft指南中所述),您應該創建一個名爲ApplicationUser的類,它繼承IdentityUser。在你的代碼

public class ApplicationUser : IdentityUser 
{ 
    [Required] 
    public string PeopleID { get; set; } 
} 

然後瞄準ApplicationUser(而不是IdentityUser):還有添加屬性

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