SQL 为一对多关系创建了不需要的列

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

我正在使用 asp.net mvc 设置数据库,但是当我运行 update-database 时,数据库自动创建了另一列 JobListingJobId 来存储 JobApplication 表的 FK 这是我所有的课程: 雇主:

public class Employer : ApplicationUser
{
    public string? Company { get; set; }
    public virtual ICollection<JobListing>? Jobs { get; set; }
}

工作申请:

public class JobApplication
{
    [Key]
    public int JobApplicationId { get; set; }
    //Attributes
    [Display(Name = "Job")]
    public int JobId { get; set; }
    [Display(Name = "Job Seeker Name")]
    public string JobSeekerId { get; set; }
    [Display(Name = "Job Seeker Name")]
    public virtual JobSeeker? JobSeeker { get; set; }
    [Display(Name = "Job")]
    public virtual JobListing? JobListing { get; set; }
}

工作类别:

public class JobCategory
{
    [Key]
    public int JobCategoryId { get; set; }
    //Attributes
    public virtual ICollection<JobListing>? JobListing { get; set; }
}

职位列表:

public class JobListing
{
    [Key]
    public int JobId { get; set; }
    //Attributes
    [Display(Name = "Employer Name")]
    public string? EmployerId { get; set; }
    [Display(Name = "Category Name")]
    public int JobCategoryId { get; set; }
    public virtual Employer? Employer { get; set; }
    public virtual JobCategory? JobCategory { get; set; }
    public virtual ICollection<JobApplication>? JobApplications { get; set; }
}

求职者:

public class JobSeeker : ApplicationUser
{
    public string? Skill { get; set; }
    public virtual ICollection<JobApplication>? JobApplications { get; set; }
}

我在ApplicationDbContext中创建了JobApplication、JobListing和JobCategory

public DbSet<JobListing> JobListings { get; set; }
public DbSet<JobCategory> JobCategories { get; set; }
public DbSet<JobApplication> JobApplications { get; set; }

后来我尝试明确指定为 JobApplication 设置 FK

builder.Entity<JobApplication>()
    .HasOne(ja => ja.JobListing)
    .WithMany(jl => jl.JobApplications)
    .HasForeignKey(ja => ja.JobId)
    .IsRequired();

但是当我运行 update-database 时它显示此错误 ALTER TABLE 语句与 FOREIGN KEY 约束“FK_JobApplications_JobListings_JobId”冲突。冲突发生在数据库“FPTJob”、表“dbo.JobListings”、列“JobId”中。

c# asp.net sql-server asp.net-mvc
1个回答
0
投票
  1. 我会将两个表中的

    JobId
    重命名为
    JobListingId
    。或者将
    JobListing
    实体重命名为
    Job

  2. 如果您的数据库中还没有数据,您可以将其删除并运行

    update-database
    以使用新代码重新创建它。

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