[英]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.