Dataannotations-inverseproperty Attribute:
We have seen in the Code-first convention sections that Code-first creates {Class name}_{primary key} foreign Key Colum n If you had not included foreign key property in a parent class. The Inverseproperty attribute is used if you have multiple relationships between classes.
Consider the following example.
PublicClassstudent{Public Student () {}Publicint StudentID {GetSet }PublicString Studentname {GetSet }Public standard currentstandard { get; set;} Public standard previousstandard { get; set;} }public class standard{public Standard () {} public int standardid {get; set;} public string standardname {get; set;} public icollection<Student> currentstudents {get; set;} public icollection<Student> previousstudents {get; set;} }
As can see in the above example, Student class includes and the navigation properties to standard class. The same is standard class includes, collection navigation properties for Student. Code-first creates four columns for this relationship, as shown below.
Inverseproperty overrides this convention and specifies alignment of the properties. The following example uses Inverseproperty in standard class to fix this problem.
PublicClassstudent{Public Student () {}Publicint StudentID {GetSet }PublicString Studentname {GetSet }Public standard currentstandard { get; set;} Public standard previousstandard { get; set;} }PublicClassstandard{public Standard () {} public int standardid {get; set;} public string standardname {get; set;} [inverseproperty ( "Currentstandard")] Public icollection<student> currentstudents { get; set;} [inverseproperty ( "Previousstandard")] Public icollection<student> previousstudents { get; set;} }
As can see in the above example, we had applied Inverseproperty attribute to currentstudents & Previousstudents p Roperty and specify which reference property of Student class it belongs to. Now, Code-first would create only the foreign key column in Student table as shown below.
You can also use ForeignKey attribute to include foreign key property with different name as shown below.
PublicClassstudent{Public Student () {}Publicint StudentID {GetSet }PublicString Studentname {GetSet }public int Currentstandardid { get; set;} public int Previousstandardid { get; set;} [ForeignKey ("Currentstandardid")] public standard currentstandard { get; set;} [ForeignKey ("Previousstandardid")] public standard previousstandard { get; set;} }PublicClassstandard{public Standard () {} public int standardid {get; set;} public string standardname {get; set;} [inverseproperty ( "Currentstandard")] Public icollection<student> currentstudents { get; set;} [inverseproperty ( "Previousstandard")] Public icollection<student> previousstudents { get; set;} }
The above example would create the following columns.
Thus, you can use Inverseproperty and ForeignKey attribute for multiple relationships between the same classes.
Dataannotations-inverseproperty Attribute: