.net core 如何在EF core中设置我的主键的外键

.net core 如何在EF core中设置我的主键的外键,.net-core,entity-framework-core,.net Core,Entity Framework Core,假设我有一个实体Car,我正在设置一个表来替换一个不可用的Car,我们称之为CarSwap,它只是一个包含两列的表,一列包含我们拥有的CarId,另一列包含替换它的CarId Class CarSwap{ public int CarId { get; set; } public int ReplacerId { get; set; } public Car Car { get; set; } } 两辆车可能被同一辆车替换, 但是一辆车只能被一辆车替换 所以我认为代表这一点的代码应

假设我有一个实体Car,我正在设置一个表来替换一个不可用的Car,我们称之为CarSwap,它只是一个包含两列的表,一列包含我们拥有的CarId,另一列包含替换它的CarId

Class CarSwap{
  public int CarId { get; set; }
  public int ReplacerId { get; set; }
  public Car Car { get; set; }
}
两辆车可能被同一辆车替换, 但是一辆车只能被一辆车替换

所以我认为代表这一点的代码应该是:

public void Configure(EntityTypeBuilder<CarSwap> builder)
{
   builder.HasKey(c => new { c.CarId }); // Key because one car can only be replaced by one car
   builder.Property(c => c.CarId ).ValueGeneratedNever();

   builder.HasOne(e => e.Car).WithOne().HasForeignKey(typeof(CarSwap), "CarId").IsRequired();
   builder.HasOne(e => e.Car).WithMany().HasForeignKey(a => a.ReplacerId).IsRequired(); // Because the replacer can replace multiple cars
}
public void配置(EntityTypeBuilder)
{
HasKey(c=>new{c.CarId});//因为一辆车只能被一辆车替换
属性(c=>c.CarId).ValueGeneratedNever();
builder.HasOne(e=>e.Car).WithOne().HasForeignKey(typeof(CarSwap),“CarId”).IsRequired();
builder.HasOne(e=>e.Car).WithMany().HasForeignKey(a=>a.ReplacerId).IsRequired();//因为替换程序可以替换多辆车
}
生成迁移时,此代码为ReplacerId而不是CarId创建正确的外键


如何让它生成正确的外键,从而不允许我添加不存在的汽车?

现在我意识到我的愚蠢错误。我没有目标去绘制被替换的汽车的地图。 我已将其更改为:

Class CarSwap{
  public int CarId { get; set; }
  public int ReplacerId { get; set; }
  public Car Car { get; set; }
  public Car Replacer { get; set; }
}
然后改变了:

builder.HasOne(e => e.Car).WithMany().HasForeignKey(a => a.ReplacerId).IsRequired(); // Because the replacer can replace multiple cars
致:

builder.HasOne(e => e.Replacer).WithMany().HasForeignKey(a => a.ReplacerId).IsRequired(); // Because the replacer can replace multiple cars