我有以下類:我可以避免實體中的外鍵屬性嗎?
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);
這一切似乎很好地工作。但是,我真的想要從Bicycle
實體中刪除BicycleManufacturerId
屬性。它只是在那裏建立FK關係。如果我刪除此屬性,是否有辦法創建正確的FK關係?通過增加對對方作爲一個集合的關係
modelBuilder.Entity<Bicycle>()
.HasRequired(a => a.BicycleManufacturer)
.WithMany()
.Map(m => m.MapKey("BicycleManufactuerId"));