将列添加到AspNetUsers表

7

工作站设置:

  • Windows 8.1 Pro
  • Visual Studio Pro 2013 v 12.0.40629.00 Update 5
  • .Net v 4.6.01055

背景:

我使用个人帐户身份验证创建了我的项目,然后按照我在Youtube上找到的指南从现有数据库创建了EDMX数据模型。我这样做是为了为我的网站创建身份验证。然后,我修改了web.config文件中的默认连接,以指向我的现有数据库。在修改默认连接后注册第一个用户帐户时,它自动生成了所有必要的AspNet表。

问题:

我需要向AspNetUsers表添加自定义列。我遵循了Microsoft的指南,可以在这里找到,但是当我执行修改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文件时,它被锁定并且无法编辑。

2个回答

7
错误意味着您没有将该列添加到模型(edmx)中的IdentityUser类/表中。
问题是,通常情况下您无法直接扩展IdentityUser,而需要从IdentityUser继承。因为在您的情况下,我怀疑AspNetUsers表是edmx的一部分。所以我猜您可以在那里添加一列来解决这个问题。但我不确定。
使用代码优先(如Microsoft指南中所述),您应该创建一个名为ApplicationUser的类,该类继承IdentityUser,并在其中添加属性:
public class ApplicationUser : IdentityUser
{
    [Required]
    public string PeopleID { get; set; }
}

现在,您需要在代码中将IdentityUser更改为ApplicationUser:

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

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接