0

I am trying to use Entity Framework to create a database table that will have two columns, one for a Person and another for a Person. In other words, there will be two foreign keys and each will point to two different records on the same table.

The one question that most nearly matches my situation isn't written well and has no answers. Most questions on StackOverflow and elsewhere deal with collections of many multiple records. In my situation, I just need to know how to set up two foreign keys to the same table on a model.

This doesn't look right to me and Visual Studio doesn't like it either, because the code references Person twice.

public class Lesson
{
    [Key]
    public int LessonId { get; set; }

    [ForeignKey("Person")]
    [Column(Order = 0)]
    public string studentId { get; set; } 
    public Person Person { get; set; }

    [ForeignKey("Person")]
    [Column(Order = 1)]
    public string teacherId { get; set; }
    public Person Person { get; set; }
}

Does this look right to you? Am I trying to solve the wrong problem? ...Or, better yet, is there just some syntax to make this work?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Gabriel Kunkel
  • 2,643
  • 5
  • 25
  • 47

1 Answers1

2

Does this look right to you?

No. Try something like:

public class Lesson
{
    [Key]
    public int LessonId { get; set; }

    [ForeignKey("Student")]
    public string StudentId { get; set; } 
    public Person Student { get; set; }

    [ForeignKey("Teacher")]
    public string TeacherId { get; set; }
    public Person Teacher{ get; set; }

}
GMB
  • 216,147
  • 25
  • 84
  • 135
David Browne - Microsoft
  • 80,331
  • 6
  • 39
  • 67