Search code examples
c#asp.net-mvcasp.net-web-apiodata

How to $expand Child entity first then Parent entity in Odata


I have 2 entities Student and courses as below.

public class Student
{
    [Key]
    public int Student_Id{ get; set; }

    [StringLength(100)]
    public string FirstName { get; set; }

    [StringLength(100)]
    public string LastName { get; set; }

    [StringLength(1)]
    public string Gender { get; set; }

     public ICollection<Course> courses{ get; set; }
   }

public class Courses
{
    [Key]
    public int Course_Id{ get; set; }

    public int Student_Id{ get; set; }

    [StringLength(100)]
    public string CourseName{ get; set; }

    [StringLength(10)]
    public string Duration { get; set; }

   }

The following $expand is working as expected.

http://localhost:61565/Odata/Student?$select=Student_Id,FirstName &$expand=Courses($select=Course_Id,CourseName)

Is there anyway I can $expand child entity "Courses" first and then Parent "Student" Even If I add the below code

   public ICollection<Student> Students{ get; set; }

to the courses. It is throwing error when I use $expand option.

Is there any way can we set navigation properties bidirectionally on both parent and child entity-sets or any other way to handle it?


Solution

  • To access in Bi-directional add ForiegnKey for Student_id in Courses as below.

      public class Courses
    {
     [Key]
    public int Course_Id{ get; set; }
     [ForeignKey("Student")]
    public int Student_Id{ get; set; }
    
     [StringLength(100)]
    public string CourseName{ get; set; }
    
     [StringLength(10)]
    public string Duration { get; set; }
    
    public virtual Student Student{ get; set;}
    
    }