ASP.NET MVC 5 Core Identity CompanyID 外键 dbo.AspNetUsers table

ASP.NET MVC 5 Core Identity CompanyID foreign key on dbo.AspNetUsers table

我有一个在 SQL 服务器数据库上使用 Core Identity 的 MVC 5 应用程序。在用户注册视图中,我想为用户分配到的公司添加一个外键下拉列表。这是一个必填字段,一个用户只能分配给一个公司。

AspNetUsers

Company Table

public class ApplicationUser : IdentityUser
{
    ....
    public int? CompanyID { get; set; }

  //  [ForeignKey("CompanyId")]
  //  public virtual Company UserCompany { get; set; }
}

我已将 CompanyID 添加到 AccountViewModels.cs

下的 RegisterViewModel
public class RegisterViewModel
{
    ....

    [Required]
    [Display(Name = "Company")]
    public int CompanyID { get; set; }

然后我将以下内容添加到 AccountController:

    using System;
    using System.Globalization;
    using System.Linq;
    using System.Security.Claims;
    using System.Threading.Tasks;
    using System.Web;
    using System.Web.Mvc;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.Owin;
    using Microsoft.Owin.Security;
    using EMS.Models;

    namespace EMS.Controllers
    {
       // [Authorize]
        public class AccountController : Controller
        {
    private ApplicationSignInManager _signInManager;
    private ApplicationUserManager _userManager;
    private ApplicationDbContext context;
    **private EMSEntities db = new EMSEntities();**

    public AccountController()
    {
        context = new ApplicationDbContext();
    }

    //
    // GET: /Account/Register
    [AllowAnonymous]
    public ActionResult Register()
    {
        **ViewBag.Company = new SelectList(db.Companies.ToList(), "ID", "CompanyName");**
        ViewBag.Name = new SelectList(context.Roles.ToList(), "Name", "Name");
        return View();
    }

    //
    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model, ApplicationUser applicationUser)
    {
        if (ModelState.IsValid)
        {
            **ViewBag.Company = new SelectList(db.Companies.ToList(), "ID", "CompanyName", model.CompanyID);**
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email, **CompanyID = model.CompanyID** };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // 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>");
                await this.UserManager.AddToRoleAsync(user.Id, model.Name);
                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

    // New Methods

        [AllowAnonymous]
        [HttpGet]
        public ActionResult RegisterRole()
    {
        ViewBag.Name = new SelectList(context.Roles.ToList(), "Name", "Name");
        ViewBag.UserName = new SelectList(context.Users.ToList(), "UserName", "UserName");
        return View();
    }

最后我将下拉列表添加到注册视图中:

<div class="form-group">
    @Html.Label("Company", new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.DropDownList("CompanyID", null, htmlAttributes: new { @class = "form-control" })
    </div>
</div>

当 运行 应用程序并尝试注册新用户时,出现以下错误:

Register user issue

尝试登录时,我在另一行收到相同的错误:

Server Error in '/' Application. The model backing the 'ApplicationDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).

有什么问题?

在程序包管理器控制台中尝试:

Enable-Migrations -ContextTypeName 'Applicationname.Data.ApplicationDbContext'
add-migration 'migrationsname'
update-database

它只是需要更新数据库。这是因为 Code First 在启用迁移之前创建了一个数据库,因此您将需要一个 initail 迁移。

谢谢 Jansen,你的回答让我走上了正轨,但并没有完全解决问题。解决问题的方法是将以下内容添加到 Application_Start 下的 Global.asax 文件中:

    Database.SetInitializer<ApplicationDbContext>(null);