我有以下课程:
public class Bicycle
{
public int BicycleId { get; set; }
public DateTime YearOfManufacture { get; set; }
public int BicycleManufactuerId { get; set; }
public BicycleManufacturer BicycleManufacturer { get; set; }
}
public class BicycleManufacturer
{
public int BicycleManufacturerId { get; set; }
public string Description { get; set; }
}
每个Bicycle
必须有BicycleManufacturer
(1:1)。某些BicycleManufacturer
可能与任何Bicycle
无关。大多数将与多个Bicycle
实体相关联。
我有以下流畅的API代码来设置FK关系:
modelBuilder.Entity<Bicycle>()
.HasRequired(a => a.BicycleManufacturer)
.WithMany()
.HasForeignKey(u => u.BicycleManufactuerId);
这一切似乎都很好。但是,我真的想从BicycleManufacturerId
实体中删除Bicycle
属性。它只是建立FK关系。如果我删除这个属性,有没有办法可以创建正确的FK关系?
答案 0 :(得分:3)
您可以删除该属性并使用映射:
modelBuilder.Entity<Bicycle>()
.HasRequired(a => a.BicycleManufacturer)
.WithMany()
.Map(m => m.MapKey("BicycleManufactuerId"));
答案 1 :(得分:0)
您也可以按惯例通过将另一方的关系添加为集合来实现。
public class Bicycle
{
public int BicycleId { get; set; }
public DateTime YearOfManufacture { get; set; }
public int BicycleManufactuerId { get; set; }
public BicycleManufacturer BicycleManufacturer { get; set; }
}
public class BicycleManufacturer
{
public int BicycleManufacturerId { get; set; }
public ICollection<Bicycle> Bicycles { get; set; }
public string Description { get; set; }
}