The foreign key attribute is used to:
Specify the name of the navigation property related to this foreign key property
// this is foreign key property with related "privilegeLookup" navigation property. Database column name will be PrivilegeLookupId [ForeignKey("privilegeLookup"), Column(Order = 1)] public int PrivilegeLookupId { get; set; } // this is related navigation property public PrivilegeLookup privilegeLookup { get; set; }
OR specify the name of the foreign key property for this navigation property:
// this is foreign key property public int PrivilegeLookupId { get; set; } // this is navigation property with related foreign key property [ForeignKey("PrivilegeLookupId")] public PrivilegeLookup privilegeLookup { get; set; }
This is useful when the standard EF rules for code are not applied or applied in a way that is not suitable for you. Here you can see the list of conditional codes of the EF code.
The Inverse Property attribute is used when you need to indicate that a navigation property in class A is associated with the same foreign key as another navigation property in class B. For instance:
public class Student { public int StudentID { get; set; } public Standard CurrentStandard { get; set; } public Standard PreviousStandard { get; set; } } public class Standard { public int StandardId { get; set; } public ICollection<Student> CurrentStudents { get; set; } public ICollection<Student> PreviousStudents { get; set; } }
Here we have two classes, each with two navigation properties. Our intention is to have two foreign keys in the Student table, probably with the names CurrentStandardId and PreviousStandardId, and the navigation properties of the Standard class are also associated with the same foreign keys (one to many relationships). However, in this case, EF will not understand this without further guidance - instead, it will create an external 4 . To drive it, we must use the inverse property attribute:
public class Standard { public int StandardId { get; set; }
Now EF understands our intentions and creates only two foreign keys, although the names will not be very good. To also change the column names, we can use the foreign key attribute:
public class Student { public int StudentID { get; set; } public int CurrentStandardId { get; set; } public int PreviousStandardId { get; set; } [ForeignKey("CurrentStandardId")] public Standard CurrentStandard { get; set; } [ForeignKey("PreviousStandardId")] public Standard PreviousStandard { get; set; } }
In short, EF can deduce many things based on code conventions. However, when it cannot (for example, when you have two foreign keys in the same class), you need to help using the attributes from your question.
source share