首页 > 解决方案 > FindByEmailAsync 中仍包含未映射的列

问题描述

我正在使用 .NET core 3.1,并且定义了以下类:

public class AspNetUsers : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    [NotMapped] public override bool TwoFactorEnabled { get; set; }
    [NotMapped] public override bool PhoneNumberConfirmed { get; set; }
    [NotMapped] public override string ConcurrencyStamp { get; set; }
    [NotMapped] public override string NormalizedEmail { get; set; }
    [NotMapped] public override string NormalizedUserName { get; set; }
}

然后我尝试使用以下(存根,尚未处理角色)登录端点:

[HttpPost]
[AllowAnonymous]
[Route("Account/Login")]
public async Task<IActionResult> Login(AspNetUsersViewModel model, string returnUrl)
{
    var validated = true;
    var message = "Invalid username or password.";
    if (ModelState.IsValid)
    {
        var user = await _userManager.FindByEmailAsync(model.Email);
        if (await _userManager.CheckPasswordAsync(user, model.Password) == false)
        {
            validated = false;
        }

        var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, true);
        if (result.Succeeded)
        {
            await _userManager.AddClaimAsync(user, new Claim("UserRole", "Admin"));
        }
        else if (result.IsLockedOut)
        {
            message = "You are locked out.";
            validated = false;
        }
        if (!validated)
        {
            ModelState.AddModelError("message", "Invalid username or password.");
            return View(message);
        }
        if (!string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl))
        {
            return Redirect(returnUrl);
        }
        return RedirectToAction("Index", "Home");
    }

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

我遇到的问题是,当我到达端点时,当它尝试运行时,我得到一个 500 响应,并带有以下异常消息FindByEmailAsync

MySqlException:“字段列表”中的未知列“a.ConcurrencyStamp”

我不确定为什么会出现异常,因为我希望通过将NotMapped属性添加到属性中,它不会包含在对数据库的请求中。

我到底错过了什么?

更新

Startup.cs 中的 ConfigureServices 如下所示:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseMySql(
            Configuration.GetConnectionString("DefaultConnection")));
    services.AddIdentity<AspNetUsers, AspNetRoles>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultUI()
        .AddDefaultTokenProviders();
    services.AddControllersWithViews();
    services.AddRazorPages().AddMvcOptions(options => options.EnableEndpointRouting = false);

    // configure the session
    services.AddSession(options =>
    {
        options.Cookie.HttpOnly = true;
    });

    // configure the identity options
    services.Configure<IdentityOptions>(options =>
    {
        // password settings
        options.Password.RequireDigit = true;
        options.Password.RequireLowercase = true;
        options.Password.RequireNonAlphanumeric = true;
        options.Password.RequireUppercase = true;
        options.Password.RequiredLength = 8;
        options.Password.RequiredUniqueChars = 1;

        // lockout settings
        options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
        options.Lockout.MaxFailedAccessAttempts = 5;
        options.Lockout.AllowedForNewUsers = false;

        // user settings
        options.User.AllowedUserNameCharacters =
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
        options.User.RequireUniqueEmail = true;
    });

    // configure the cookie options
    services.ConfigureApplicationCookie(options =>
    {
        options.Cookie.HttpOnly = true;
        options.ExpireTimeSpan = TimeSpan.FromHours(1);

        options.LoginPath = "/Account/Login";
        options.AccessDeniedPath = "/Identity/Account/AccessDenied";
        options.SlidingExpiration = true;
    });

    // configure the auth controller
    services.AddAuthorization(options =>
    {
        options.AddPolicy("Authorized", policy => policy.Requirements.Add(new AuthController()));
    });
    services.AddSingleton<IAuthorizationHandler, LoggedIn>();
}

标签: c#entity-framework-coreasp.net-core-mvc

解决方案


推荐阅读