using System.ComponentModel.DataAnnotations.Schema;
public class Department
{
...
public virtual ICollection<Employee> PrimaryEmployees { get; set; }
public virtual ICollection<Employee> SecondaryEmployees { get; set; }
}
public class Employee
{
...
[InverseProperty("PrimaryEmployees")]
public virtual Department PrimaryDepartment { get; set; }
[InverseProperty("SecondaryEmployees")]
public virtual Department SecondaryDepartment { get; set; }
}
InverseProperty can be used to identify two way relationships when multiple two way relationships exist between two entities.
It tells Entity Framework which navigation properties it should match with properties on the other side.
Entity Framework doesn't know which navigation property map with which properties on the other side when multiple bidirectional relationships exist between two entities.
It needs the name of the corresponding navigation property in the related class as its parameter.
This can also be used for entities that have a relationship to other entities of the same type, forming a recursive relationship.
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public class TreeNode
{
[Key]
public int ID { get; set; }
public int ParentID { get; set; }
...
[ForeignKey("ParentID")]
public TreeNode ParentNode { get; set; }
[InverseProperty("ParentNode")]
public virtual ICollection<TreeNode> ChildNodes { get; set; }
}
Note also the use of the ForeignKey
attribute to specify the column that is used for the foreign key on the table. In the first example, the two properties on the Employee
class could have had the ForeignKey
attribute applied to define the column names.