簡體   English   中英

dbo.AspNetUsers 表上的 ASP.NET MVC 5 核心標識 CompanyID 外鍵

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

我有一個 MVC 5 應用程序,它在 SQL 服務器數據庫上使用 Core Identity。 在用戶注冊視圖中,我想為用戶分配到的公司添加一個外鍵下拉列表。 這是一個必填字段,一個用戶只能分配到一個公司。

AspNet用戶

公司表

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

最后,我將下拉列表添加到 Register 視圖:

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

運行應用程序並嘗試注冊新用戶時,出現以下錯誤:

注冊用戶問題

嘗試登錄時,我在另一行遇到相同的錯誤:

“/”應用程序中的服務器錯誤。 自數據庫創建以來,支持“ApplicationDbContext”上下文的模型已更改。 考慮使用 Code First 遷移來更新數據庫 ( http://go.microsoft.com/fwlink/?LinkId=238269 )。

問題是什么?

在包管理器控制台中嘗試:

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

它只需要更新數據庫。 這是因為 Code First 在啟用遷移之前創建了一個數據庫,因此您需要進行初始遷移。

謝謝詹森,你的回答讓我走上了正軌,但並沒有完全解決問題。 解決該問題的方法是將以下內容添加到 Application_Start 下的 Global.asax 文件中:

    Database.SetInitializer<ApplicationDbContext>(null); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM