【问题标题】:ASP.NET MVC 5 Core Identity CompanyID foreign key on dbo.AspNetUsers tabledbo.AspNetUsers 表上的 ASP.NET MVC 5 Core Identity CompanyID 外键
【发布时间】:2020-06-04 01:54:32
【问题描述】:

我有一个在 SQL Server 数据库上使用 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

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

“/”应用程序中的服务器错误。支持的模型 'ApplicationDbContext' 上下文已更改,因为数据库是 创建的。考虑使用 Code First 迁移来更新数据库 (http://go.microsoft.com/fwlink/?LinkId=238269)。

有什么问题?

【问题讨论】:

    标签: c# asp.net sql-server asp.net-mvc-5 asp.net-core-identity


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

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

          Database.SetInitializer<ApplicationDbContext>(null); 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-24
        • 2016-10-28
        • 2014-04-04
        • 1970-01-01
        • 2014-02-18
        • 2022-07-08
        • 2014-04-30
        • 2022-01-04
        相关资源
        最近更新 更多