我想在MVC項目上首先使用註釋(首次)執行代碼。如何創建一個具有組合鍵的表,其中每個成員都是其他表的外鍵成員
我已經創建了以下POCO。
[Table("Customers")]
public partial class Customer
{
public int Id { get; set; }
[Required]
[DisplayName("First Name")]
public string FirstName { get; set; }
[DisplayName("Last Name")]
[Required]
public string LastName { get; set; }
//other properties...
}
[Table("Vehicles")]
public partial class Vehicle
{
[Required]
public int Id { get; set; }
[Required]
public int CustomerId { get; set; }
[Required]
public string Make { get; set; }
[Required]
public string Model { get; set; }
[Required]
public string Year { get; set; }
//other fields
[ForeignKey("CustomerId")]
public virtual Customer Customer { get; set; }
}
[Table("CustomerAppointments")]
public partial class CustomerAppointment
{
[Key,Column(Order=0)]
public int CustomerId { get; set; }
[Key,Column(Order=1)]
public int VehicleId { get; set; }
public DateTime? AppointmentDate { get; set; }
public DateTime? AppointmentTime { get; set; }
public string AvailableDays { get; set; }
//other fields
[ForeignKey("CustomerId")]
public virtual Customer Customer { get; set; }
[ForeignKey("VehicleId")]
public virtual Vehicle Vehicle { get; set; }
}
我覺得我的意圖很明顯。我有客戶。那些客戶擁有車輛。我想創建一個CustomerAppointments表,其中客戶和其中一個客戶車輛計劃提供服務。
爲了記錄,這不是整個模型,並已被簡化爲問題的目的。
我正在使用MvcScaffolding構建EF項目和視圖。
一切編譯,但是當我嘗試導航到客戶頁面中我收到以下錯誤(其實沒有提及引用的客戶類)...
Introducing FOREIGN KEY constraint 'FK_dbo.CustomerAppointments_dbo.Vehicles_VehicleId' on table 'CustomerAppointments' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
我已經嘗試了不同的註解,甚至試圖使用這樣的流利API ...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<CustomerAppointment>()
.HasRequired(ca => ca.Customer)
.WithRequiredPrincipal()
.WillCascadeOnDelete(false);
modelBuilder.Entity<CustomerAppointment>()
.HasRequired(ca => ca.Vehicle)
.WithRequiredPrincipal()
.WillCascadeOnDelete(false);
}
但我不能讓它工作。我已經閱讀了我可以在google和so上找到的所有示例,但無濟於事。
PS ...如果這隻適用於註釋,那隻會是我的偏好。
在這種情況下它不起作用,因爲'CustomerId'和'VehicleId'是主鍵的一部分,不能爲空。 – Slauma
@Slauma更正,謝謝你指出。正如你在答案中所述,奇怪的是擁有這個組合鍵。 –