[英]One to zero or one relationship entity framework
I am trying to enforce a one to (zero or one) table relationship using code first/fluent api and the intended table is as below. 我试图使用代码优先/流利的api来强制一对一(零或一个)表关系,预期的表如下。
Student may only have a contact (StudentContact) or not But Every contact (StudentContact) must have a Student 学生只能有一个联系人(StudentContact),但每个联系人(StudentContact)都必须有一个学生
StudentID StudentName
1 StudentA
2 StudentB
StudentContactID StudentContact StudentID
1 123456789 1
2 123456789 2
I tried to use 我尝试使用
EntityName<Student>().HasOptional(x => x.StudentContact).WithRequired(l => l.Student)
but unfortunately it does not enforce a one relationship for StudentID column, meaning that StudentID column may contain duplicate value. 但不幸的是,它没有对StudentID列强制采用单一关系,这意味着StudentID列可能包含重复值。
reference: One to zero/one relation in entity framework code first 参考: 首先是实体框架代码中的一对零/一个关系
When you are configuring one-to-one relationships, Entity Framework requires that the primary key of the dependent ( StudentContact
) also be the foreign key. 在配置一对一关系时,实体框架要求从属的主键( StudentContact
)也应为外键。 The proper way to achieve what you want could be this, but is using Data Annotations: 实现所需目标的正确方法可能是以下方法,但是正在使用数据注释:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public StudentContact StudentContact { get; set; }
}
public class StudentContact
{
[Key, ForeignKey("Student")]
public int StudentId { get; set; }
public int Contact { get; set; }
public Student Student { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.