2
votes

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 Persons 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; }
}
2
Does it make sense to derive Note from Doctor? I would model your classes logically and independently from the ORM. You wouldn't use inheritance just for creating a relationship. - user2697817
Yes you'r right ....its just a sample code ...my main question is this:is that true to create all foreign keys using inheritance instead of using virtual properties? - Iman Salehi
No, you would definitely not want to do this. Also, you can only create 1-2-1 relationships this way. - user2697817
thanks for your comment. - Iman Salehi

2 Answers

0
votes

You'd only want to derive from Doctor, when you need to expand the Doctor type by adding to it additional properties, let's say Surgeon.

In your case, whether you want to attach a single or multiple notes to a doctor, is merely another property to ANY type of doctor.

So you should wither add a nullable/non-nullable string property or complex type Note in the Doctor type for a single note, or as you suggested yourself, a collection of Note each having its own ID.

0
votes

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.