If you have an Order class, adding a property that refers to another class in your model, for example, Customer should be enough so that EF knows the relationship there:
public class Order { public int ID { get; set; }
You can always set the FK relation explicitly:
public class Order { public int ID { get; set; } // Some other properties // Foreign key to customer [ForeignKey("Customer")] public string CustomerID { get; set; } public virtual Customer Customer { get; set; } }
The ForeignKeyAttribute constructor takes a string as a parameter: if you put it on a foreign key property, it represents the name of the associated navigation property. If you put it in a navigation property, it represents the name of the associated foreign key.
This means that if you put ForeignKeyAttribute in the Customer property, the attribute will take CustomerID in the constructor:
public string CustomerID { get; set; } [ForeignKey("CustomerID")] public virtual Customer Customer { get; set; }
EDIT based on the last code You get this error because of this line:
[ForeignKey("Parent")] public Patient Patient { get; set; }
EF will look for a property called Parent to use as a foreign key tool. You can do 2 things:
1) Remove ForeignKeyAttribute and replace it with RequiredAttribute to mark the relationship as necessary:
[Required] public virtual Patient Patient { get; set; }
Decorating a property with RequiredAttribute also has a nice side effect: a relation in the database is created using ON DELETE CASCADE .
I would also recommend making the property virtual to enable Lazy Loading.
2) Create a property called Parent that will serve as a foreign key. In this case, it probably makes sense to call it, for example, ParentID (you will also need to change the name in ForeignKeyAttribute ):
public int ParentID { get; set; }
In my experience, in this case, although itβs better to work with it differently:
[ForeignKey("Patient")] public int ParentID { get; set; } public virtual Patient Patient { get; set; }