INSERT 语句与 ASP.NET Core MVC 中 AspNetUsers(IdentityUser) 的 FOREIGN KEY 约束 Id 冲突

问题描述 投票:0回答:1

我为医生、患者和管理员创建了一个注册面板,当我尝试注册或插入数据时,它给出了这样的错误,

SqlException:INSERT 语句与 FOREIGN KEY 约束“FK_AspNetUsers_Departments_DepartmentId”冲突。冲突发生在数据库“Hospitaldb”,表“dbo.Departments”,列“Id”

迁移部分:

migrationBuilder.CreateTable(
    name: "AspNetUsers",
    columns: table => new
    {
        Id = table.Column<string>(type: "nvarchar(450)", nullable: false),
        Discriminator = table.Column<string>(type: "nvarchar(21)", maxLength: 21, nullable: false),
        UserName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
        NormalizedUserName = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
        Email = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
        NormalizedEmail = table.Column<string>(type: "nvarchar(256)", maxLength: 256, nullable: true),
        EmailConfirmed = table.Column<bool>(type: "bit", nullable: false),
        PasswordHash = table.Column<string>(type: "nvarchar(max)", nullable: true),
        SecurityStamp = table.Column<string>(type: "nvarchar(max)", nullable: true),
        ConcurrencyStamp = table.Column<string>(type: "nvarchar(max)", nullable: true),
        PhoneNumber = table.Column<string>(type: "nvarchar(max)", nullable: true),
        PhoneNumberConfirmed = table.Column<bool>(type: "bit", nullable: false),
        TwoFactorEnabled = table.Column<bool>(type: "bit", nullable: false),
        LockoutEnd = table.Column<DateTimeOffset>(type: "datetimeoffset", nullable: true),
        LockoutEnabled = table.Column<bool>(type: "bit", nullable: false),
        AccessFailedCount = table.Column<int>(type: "int", nullable: false),
    
        // I Added This Line
        DepartmentId = table.Column<int>(type: "int", nullable: true)
    },
    constraints: table =>
    {
        table.PrimaryKey("PK_AspNetUsers", x => x.Id);

        // I Added This Code Block
        table.ForeignKey(
        name: "FK_AspNetUsers_Departments_DepartmentId",
        column: x => x.DepartmentId,
        principalTable: "Departments",
        principalColumn: "Id",
        onDelete: ReferentialAction.Cascade);
    });
}

部门模型类:

public class Department
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public ICollection<ApplicationUser> Employees { get; set; }
}

DbInitializer继承自

IDbInitializer
:

public void Initialize()
{
    try
    {
        if (_context.Database.GetPendingMigrations().Count() > 0)
        {
            _context.Database.Migrate();
        }
    }
    catch (Exception)
    {
        throw;
    }

    if (!_roleManager.RoleExistsAsync(WebsiteRoles.Website_Admin).GetAwaiter().GetResult())
    {
        _roleManager.CreateAsync(new IdentityRole(WebsiteRoles.Website_Admin)).GetAwaiter().GetResult();
        _roleManager.CreateAsync(new IdentityRole(WebsiteRoles.Website_Patient)).GetAwaiter().GetResult();
        _roleManager.CreateAsync(new IdentityRole(WebsiteRoles.Website_Doctor)).GetAwaiter().GetResult();

        _userManager.CreateAsync(new ApplicationUser
        {
            UserName = "XYZ",
            Email = "[email protected]"
        }, "XYZ@123").GetAwaiter().GetResult();

        var Appuser = _context.ApplicationUsers.FirstOrDefault(x => x.Email == "[email protected]");
        if (Appuser != null)
        {
            _userManager.AddToRoleAsync(Appuser, WebsiteRoles.Website_Admin).GetAwaiter().GetResult();
        }
    }
}

ApplicationUser
班级:

public class ApplicationUser : IdentityUser
{
    public string Name { get; set; }
    public Gender Gender { get; set; }
    public string Nationality { get; set; }
    public string Address { get; set; }
    public DateTime DOB { get; set; }
    public string Specialist { get; set; }
    public bool IsDoctor { get; set; }
    public string PictureUrl { get; set; }
    public Department Department { get; set; }
    [NotMapped]
    public ICollection<Appointment> Appointments { get; set; }
    [NotMapped]
    public ICollection<Payroll> Payrolls { get; set; }
    [NotMapped]
    public ICollection<PatientReport> PatientReports { get; set; }
}

DoctorRegister.cs
IdentityUser
的文件:

public async Task<IActionResult> OnPostAsync(string returnUrl = null) {
    returnUrl ??= Url.Content("~/");
    ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

    if (ModelState.IsValid)
    {
        var user = CreateUser();

        await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None);
        await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None);

        user.Name = Input.Name;
        user.Address = Input.Address;
        user.Nationality = Input.Nationality;
        user.DOB = Input.DOB;
        user.Gender = Input.Gender;
        user.IsDoctor = Input.IsDoctor;
        user.Specialist = Input.Specialist;
        ImageOpertaions image = new ImageOpertaions(_env);
        string filename = image.ImageUpload(Input.PictureUrl);
        user.PictureUrl = filename;

        var result = await _userManager.CreateAsync(user, Input.Password);

        if (result.Succeeded)
        {
            _logger.LogInformation("User created a new account with password.");
            await _userManager.AddToRoleAsync(user, WebsiteRoles.Website_Doctor);

            var userId = await _userManager.GetUserIdAsync(user);
            //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
            //code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
            //var callbackUrl = Url.Page(
            //    "/Account/ConfirmEmail",
            //    pageHandler: null,
            //    values: new { area = "Identity", userId = userId, code = code, returnUrl = returnUrl },
            //    protocol: Request.Scheme);

            //await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
            //    $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

            if (_userManager.Options.SignIn.RequireConfirmedAccount)
            {
                return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl });
            }
            else
            {
                await _signInManager.SignInAsync(user, isPersistent: false);
                return LocalRedirect(returnUrl);
            }
        }

        foreach (var error in result.Errors)
        {
            ModelState.AddModelError(string.Empty, error.Description);
        }
    }

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

创建用户方法:

private ApplicationUser CreateUser()
{
    try
    {
        return Activator.CreateInstance<ApplicationUser>();
    }
    catch
    {
        throw new InvalidOperationException($"Can't create an instance of '{nameof(IdentityUser)}'. " +
            $"Ensure that '{nameof(IdentityUser)}' is not an abstract class and has a parameterless constructor, or alternatively " +
            $"override the register page in /Areas/Identity/Pages/Account/Register.cshtml");
    }
}

当我调试代码时,它在此行之后抛出错误

var result = await _userManager.CreateAsync(user, Input.Password);

我打算尝试使用外键向数据库中插入一行数据,但是当我提交数据 FOREIGN KEY 约束 Id 时出现错误

我硬编码的数据库中已存在一条记录

c# asp.net-core-mvc foreign-keys asp.net-identity
1个回答
0
投票

我只是将此属性添加到我的 ApplicationUser 中。

公共int?部门 ID { 获取;放; }

我将这些内容添加到我的 AppDbContext.cs 文件中 protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder);

    // Configure the relationship between ApplicationUser and Department
    modelBuilder.Entity<ApplicationUser>()
        .HasOne(u => u.Department)
        .WithMany()
        .HasForeignKey(u => u.DepartmentId);

    modelBuilder.Entity<ApplicationUser>()
    .Property(u => u.DepartmentId)
    .ValueGeneratedOnAdd();
}

它的工作完美地创建了用户,数据也显示在 SQL 表中,我不知道它是如何通过在 ApplicationUser I 中实现新的 DepartmentId 属性来工作的。

但是我还有一个问题,那就是在 ApplicationUser 中实现新的 DepartmentId 属性,然后它是如何工作的......

© www.soinside.com 2019 - 2024. All rights reserved.