INSERT 语句与 asp.net core mvc 中的 FOREIGN KEY 约束冲突

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

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

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

迁移部分

migrationBuilder.CreateTable(
    name: "Departments",
    columns: table => new
    {
        Id = table.Column<int>(type: "int", nullable: false)
            .Annotation("SqlServer:Identity", "1, 1"),
        Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
        Description = table.Column<string>(type: "nvarchar(max)", nullable: false)
    },
    constraints: table =>
    {
        table.PrimaryKey("PK_Departments", x => x.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),
        Name = table.Column<string>(type: "nvarchar(max)", nullable: true),
        Gender = table.Column<int>(type: "int", nullable: true),
        Nationality = table.Column<string>(type: "nvarchar(max)", nullable: true),
        Address = table.Column<string>(type: "nvarchar(max)", nullable: true),
        DOB = table.Column<DateTime>(type: "datetime2", nullable: true),
        Specialist = table.Column<string>(type: "nvarchar(max)", nullable: true),
        IsDoctor = table.Column<bool>(type: "bit", nullable: true),
        PictureUrl = table.Column<string>(type: "nvarchar(max)", nullable: true),
        DepartmentId = table.Column<int>(type: "int", 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)
    },
    constraints: table =>
    {
        table.PrimaryKey("PK_AspNetUsers", x => x.Id);
        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; }
}

应用程序用户类

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

应用程序用户类

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; }
}
c# asp.net-mvc asp.net-core foreign-keys sqlexception
1个回答
0
投票

您遇到的错误表明您正在尝试将一条记录插入到

AspNetUsers
表中,其中
DepartmentId
不存在于
Departments
表中。发生这种情况是因为两个表之间有外键约束,并且您尝试插入到
AspNetUsers.DepartmentId
中的值必须与现有
Departments.Id
匹配。

您可以采取以下几个步骤来解决此问题:

确保您尝试分配给用户的

DepartmentId
实际上存在于“部门”表中。

在插入新用户之前,请检查您尝试插入的

DepartmentId
的值。确保它对应于 Departments 表中的有效 ID。

在ApplicationUser中处理DepartmentId: 在

ApplicationUser
类中,确保包含
DepartmentId
属性并将其注释为外键。确保它与 Department 类中 Id 属性的数据类型匹配。

public class ApplicationUser : IdentityUser
{
    // Other properties...

    public int DepartmentId { get; set; }

    [ForeignKey("DepartmentId")]
    public Department Department { get; set; }
}

处理部门导航属性: 在 Department 类中,确保您有用户的导航属性。

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

种子部门优先: 如果您要播种数据,请确保在播种用户之前先播种部门。

// Seed departments
context.Departments.Add(new Department { Name = "DepartmentName", Description = "DepartmentDescription" });
context.SaveChanges();

// Seed users
context.Users.Add(new ApplicationUser { /* user properties, including DepartmentId */ });
context.SaveChanges();

通过执行以下步骤,您可以确保分配给用户的

DepartmentId
有效并且存在于 Departments 表中。另外,请确保在数据播种或添加新用户时正确处理关系。

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