[英]How to create optional constraint in a one to one relationship using Entity Framework Code First
在這種情況下,如何設置外鍵(最好使用數據注釋):
[Table("Teacher", Schema = "Account")]
public partial class Teacher
{
[Key]
public int teacherId { get; set; }
public string name { get; set; }
public virtual Address Address { get; set; }
}
[Table("Student", Schema = "Account")]
public partial class Student
{
[Key]
public int studentId { get; set; }
public string name { get; set; }
public virtual Address Address { get; set; }
}
學生和教師這兩個表都有一個地址。
[Table("Address", Schema = "Location")]
public partial class Address
{
[Key]
public int addressId { get; set; }
public string details { get; set; }
public virtual Student Student { get; set; }
public virtual Teacher Teacher { get; set; }
}
表地址應對“教師”或“學生”表具有約束,這意味着“地址”表中的每一行都必須鏈接到“學生”或“教師”。
我只是找不到實現這一目標的方法。 使用當前代碼,添加遷移時出現錯誤:無法確定類型'Student'和'Address'之間的關聯的主要終點。 必須使用關系流利的API或數據注釋顯式配置此關聯的主要端。
您可以通過兩種方式實現。 1.無需在Address類上添加導航屬性。
[Table("Teacher", Schema = "Account")]
public partial class Teacher
{
[Key]
public int teacherId { get; set; }
public string name { get; set; }
public virtual Address Address { get; set; }
}
[Table("Student", Schema = "Account")]
public partial class Student
{
[Key]
public int studentId { get; set; }
public string name { get; set; }
public virtual Address Address { get; set; }
}
[Table("Address", Schema = "Location")]
public partial class Address
{
[Key]
public int addressId { get; set; }
public string details { get; set; }
}
將創建兩個關系表Student-Address和Teacher-Address。 2.您可以使用可為空的外鍵屬性。 像這樣;
[Table("Address", Schema = "Location")]
public partial class Address {
[Key]
public int addressId { get; set; }
public string details { get; set; }
public int? teacherId { get; set; }
public int? studentId { get; set; }
[ForeignKey("studentId")]
public virtual Student Student { get; set; }
[ForeignKey("teacherId")]
public virtual Teacher Teacher { get; set; }
}
順便說一句,如果您有興趣實現這種方式,可以在Code-First中查看繼承策略 。 通過使用繼承策略,您可以創建一個主類並從中繼承Student和Teacher類。 之后,在Address上將主類ID用作FK。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.