Sql 异常:列名称“NormalizedUserName”无效

Sql Exeption: Invalid column name "NormalizedUserName

我是 asp.net 核心的新手,我用 Asp.Net Core 2.2 +EF 创建了一个应用程序,使用 Identity Core 创建了一个注册页面,我在 运行 之后收到了这个错误该应用程序并引入了一些测试数据(电子邮件,密码):

SqlException: Invalid column name 'NormalizedUserName'.
              Invalid column name 'AccessFailedCount'.
              Invalid column name 'ConcurrencyStamp'.
              Invalid column name 'Email'.
              Invalid column name 'EmailConfirmed'.
              Invalid column name 'LockoutEnabled'.
              Invalid column name 'LockoutEnd'.
              Invalid column name 'NormalizedEmail'.
              Invalid column name 'NormalizedUserName'.
              Invalid column name 'PasswordHash'.
              Invalid column name 'PhoneNumber'.
              Invalid column name 'PhoneNumberConfirmed'.
              Invalid column name 'SecurityStamp'.
              Invalid column name 'TwoFactorEnabled'.
              Invalid column name 'UserName'.

我创建了一个 table,但我的列没有像上面那样命名(我的列只有 "EmailAddress" 和 "Password")

帐户控制器(忽略登录方法):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc;
using XmlViewer.Models;
using XmlViewer.ViewModels;

namespace XmlViewer.Controllers
{
    public class AccountController : Controller
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;

        public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
        }

        [HttpGet]

        [HttpGet]

        public IActionResult Login()
        {
            return View();
        }
        [HttpPost]

        public async Task<IActionResult> Login(LoginViewModel vm)//model binding
        {
            //date din vm sunt bune:
            if(ModelState.IsValid)
            {
                var result = await _signInManager.PasswordSignInAsync(vm.Email, vm.Password, vm.RememberMe, false);//folosit para pt IsPersistent(BOOL)
                if(result.Succeeded)
                {
                    return RedirectToAction("Privacy", "Home");
                }
                ModelState.AddModelError("","Invalid Login. Please Check your username/email or password.");
                return View(vm);
            }
            return View(vm);
        }

        public IActionResult Register()
        {
            return View();
        }

        [HttpPost]

        public async Task<IActionResult> Register(RegisterViewModel vm)//model binding
        {
            if (ModelState.IsValid)
            {

                var user = new ApplicationUser { UserName = vm.Email, Email = vm.Email };
                var result = await _userManager.CreateAsync(user, vm.Password);

                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, false);
                    return RedirectToAction("Index", "Home");

                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError("", error.Description); //erori de inregistrare in cont
                    }//iterare prin fiecare eroare

                }
            }
            return View(vm);
        }
    }
}

上下文模型:

    using Microsoft.AspNetCore.Identity;
    using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;


    namespace XmlViewer.Models
    {
    public class XmlViewerContext : IdentityDbContext<ApplicationUser>
    {
        //constructor
        //added migration Initial-Migration:tabelul de date in DB se creeaza dupa
        public XmlViewerContext(DbContextOptions<XmlViewerContext> options) : base(options)
        {

        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<ApplicationUser>().ToTable("Register").Property(p => p.Id).HasColumnName("EmailAddress"); ;
            modelBuilder.Entity<ApplicationUser>().ToTable("Register").Property(p => p.Id).HasColumnName("Password");



        }
    }
}

启动:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using XmlViewer.Models;
using Microsoft.AspNetCore.Identity;

namespace XmlViewer
{
    public class Startup
    {
        public static int Progress { get; set; }
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<XmlViewerContext>()
                .AddDefaultTokenProviders();
            services.AddDbContext<XmlViewerContext>(options => options.UseSqlServer(@"Data Source = (localdb)\ProjectsV13; Initial Catalog = XmlViewer; Integrated Security = True; Connect Timeout = 30;"));
            //Alta baza de date nu master
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Account}/{action=Register}/{id?}");
            });
        }
    }
}

当您构建 Identity 时(通过单击 visual studio 中的 "individual user account"),它会为您生成模型。您需要 运行 在 该模型 上进行迁移。这将创建包含您缺少的列的 AspNet* 表。 看起来你手动创建了这些表,没有 Microsoft Identity 期望的列

@AlexGodo 我知道这个话题很老了,但它可能会帮助那些将 ASP.NET 项目移动到 ASP.NET Core 的人,他们不想使用迁移,只是连接到现有的 AspNet* tables。 要解决缺少列的问题,只需将它们添加到 AspNetUsers table(例如通过 SSMS):

我缺少 4 列,其中 NormalizedUserName 是重要的一列(随机数据类型 - TBC):

NormalizedUserName nvarchar(256), null
NormalizedEmail nvarchar(256), null
LockoutEnd datetime, null
ConcurrencyStamp nvarchar(256), null

为了能够登录,我 运行 更新以填充 NormalizedUserName 列,如下所示:

update AspNetUsers
   set NormalizedUserName = UPPER(Email)
where NormalizedUserName is null

注意:通过ASP.NET核心网站登录后PasswordHash栏条目发生变化,因此将无法再通过旧网站登录. (如果需要,最好备份此列。)

希望这对您有所帮助。