【问题标题】:How to $expand Child entity first then Parent entity in Odata如何在 Odata 中先扩展子实体然后扩展父实体
【发布时间】:2019-01-24 23:15:29
【问题描述】:

我有 2 个实体学生和课程如下。

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; }

   }

以下 $expand 正在按预期工作。

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

无论如何我可以先 $expand 子实体“Courses”然后再扩展父“Student”吗 即使我添加以下代码

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

到课程。当我使用 $expand 选项时,它会抛出错误。

有什么方法可以在父实体集和子实体集上双向设置导航属性或任何其他方式来处理它?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-web-api odata


    【解决方案1】:

    你说得对,Course(s) 类应该包含一个学生的 ICollection。 我认为 URL 应该是这样的:

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

    这是一个关于实时 OData 端点的示例:

    https://demos.telerik.com/kendo-ui/service-v4/odata/Categories
        ?$top=20
        &$select=CategoryName
        &$expand=Products(
            $select=ProductName,Category;
            $expand=Category(
                $select=CategoryName))
    

    你遇到了什么错误?

    【讨论】:

    • 感谢您分享示例,它帮助了我。要解决这个问题,我们必须在 Courses 中为 Student_Id 添加 ForiegnKey 约束,然后它才能工作。
    【解决方案2】:

    要双向访问,请在 Courses 中为 Student_id 添加 ForiegnKey,如下所示。

      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;}
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-11
      • 1970-01-01
      • 1970-01-01
      • 2021-03-22
      相关资源
      最近更新 更多