by using Table per Type (TPT) inheritance in Entity Framework codefirst
we can create foreign keys like this :
public abstract class Person
{
public int id { get; set; }
public string Name { get; set; }
public string Family { get; set; }
}
[Table("Doctors")]
public class Doctor : Person
{
public string ExpertTitle { get; set; }
}
[Table("Notes")]
public class Note : Doctor
{
public string Content { get; set; }
}
in above code In addition to the creating Doctors
table and relating that with Person
s table, we could create Note
table and create 1-to-Many relation between Doctors
Table and that.
but is that standard to create all foreign keys using inheritance instead of using virtual properties like what you see bellow?!
public class Doctor : Per
{
public string ExpertTitle { get; set; }
public virtual ICollection<Note> Notes { get; set; }
}
public class Note : Doctor
{
public string Content { get; set; }
public virtual Doctor Doctor { get; set; }
}
we could create Note table and create 1-to-Many relation between Doctors Table and that.
If Note inherits from Doctor, then you have a 1/0 to 1 relationship from Note to Doctor, not a 1 to many.
Even if your goal is to create that 1/0 to 1 relationship, you should only use inheritance to do so when it truly represents a "is a" relationship. "Note is a Doctor" doesn't really make sense.
To accomplish a 1/0 to 1 relationship without inheritance, use a shared primary key which you can fidn plenty of other questions covering. Both Note and Doctor would have the same primary key. I.e. Doctor id 45 would have Note with Id 45. Since the Note is the optional 1/0 side of the relationship, then your FK constraint would be from the Note table referencing the Doctor table. Meaning you could not insert Note with Id 46 unless Doctor with Id 46 already existed.