vincentsty
vincentsty

Reputation: 3221

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.

Student may only have a contact (StudentContact) or not But Every contact (StudentContact) must have a Student

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.

reference: One to zero/one relation in entity framework code first

Upvotes: 0

Views: 514

Answers (1)

ocuenca
ocuenca

Reputation: 39326

When you are configuring one-to-one relationships, Entity Framework requires that the primary key of the dependent (StudentContact) also be the foreign key. 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; }
}

Upvotes: 4

Related Questions