Pascal
Pascal

Reputation: 12855

Create a 1 to 1 relation when the Primary Key consist of 2 keys with entity framework

I have an 1 to 1 relation between 3 tables.

The parent table has 2 primary keys (composite keys). Lets name them StudentId1 and StudentId2.

What is with the related table where I would put the

  [Key, ForeignKey("Student")]
    public int StudentId { get; set; }

I do not only have ONE property!

Should I do it like that? Writing StudentId1StudentId2 as Key property for the related Table doesn`t make sense.

RelatedTable:

[Key, ForeignKey("Student")]
public int StudentId1 { get; set; }

[Key, ForeignKey("Student")]
public int StudentId2 { get; set; }

traditional sample:

public class Student
{
    public Student() { }

    public int StudentId { get; set; }
    public string StudentName { get; set; }

    public virtual StudentAddress StudentAddress { get; set; }

}



public class StudentAddress 
{
    [Key, ForeignKey("Student")]
    public int StudentId { get; set; }

    public virtual Student Student { get; set; }
}

Upvotes: 0

Views: 72

Answers (1)

jjj
jjj

Reputation: 4997

Shouldn't Column(Order = X) work?

public class Student
{   
    [Key, Column(Order = 0)]
    public int StudentId1 { get; set; }

    [Key, Column(Order = 1)]
    public int StudentId2 { get; set; }

    public virtual StudentAddress StudentAddress { get; set; }
}


public class StudentAddress 
{
    [Key, ForeignKey("Student"), Column(Order = 0)]
    public int StudentId1 { get; set; }

    [Key, ForeignKey("Student"), Column(Order = 1)]
    public int StudentId2 { get; set; }

    public virtual Student Student { get; set; }
}

See

Upvotes: 1

Related Questions