An Enthusiastic Programmer

Data Annotation - InverseProperty Attribute

|

The Inverse property attribute is used to denote the inverse navigation property of a relationship when the same type takes part in multipart relationships.

  • The InverseProperty attribute is used when two entities have more than one relationship.
  • For Example, in the Student class, you may want to track the the online class as well as the offline class.
public class Classroom
{
    public int id { set; get; }

    public List<Student> all_offlineline_students { set; get; }

    public List<Student> all_online_students { set; get; }
}
public class Student
{
    public int id { set; get; }

    public Classroom offline { set; get; }

    public Classroom online { set; get; }
}

The above code will make Entity Framework Core confused. The Student class has two navigation reference properties. The Code First convention mechanism doesn’t know to use which one to establish a relationship with one of the navigation properties in the Classroom class.

An expected error will be thrown out when trying to execute the command Add-Migration by force.

Unable to determine the relationship represented by navigation property 'Classroom.all_offlineline_students' of type 'List<Student>'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

To achieve this purpose, we can apply an InverseProperty above on the collection properties in the Classroom class to specify their corresponding inverse properties in the Student class.

public class Classroom
{
    public int id { set; get; }
    [InverseProperty("offline")]
    public List<Student> all_offlineline_students { set; get; }
    [InverseProperty("online")]
    public List<Student> all_online_students{ set; get; }
}
public class Student
{
    public int id { set; get; }
    public Classroom offline { set; get; }
    public Classroom online { set; get; }
}

Alt

Comments