无法包含导航属性(该属性为null)

时间:2018-07-22 12:34:31

标签: asp.net-web-api entity-framework-core

我试图从数据库中获取学生,并包括与他们相对应的课程实体,但看来我做错了。

这是学生班:

public class Student
{
    public int StudentID { get; set; }

    public string Name { get; set; }

    public int CourseID { get; set; }  

    public virtual Course Course { get; set; }
}

这是课程:

public class Course
{
    public int CourseID { get; set; }

    public string Name { get; set; }

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

我检索了学生实体的集合,如下所示:

context.Students.Include(i => i.Course).ToList();

如果删除include方法,则会获取数据,但学生对象的课程属性为null。

P.S我正在用Postman进行测试,而在“包含”下我什么也收不到。

如果我对此发表评论

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

一切正常。

我将完整代码放在github上:

https://github.com/AlexDev5/Problem

2 个答案:

答案 0 :(得分:0)

您必须配置序列化程序以忽略项目中的循环引用。

为此,您必须在ConfigureServices的{​​{1}}方法内添加以下代码行

喜欢

Startup.cs

答案 1 :(得分:0)

根据此处找到的示例https://github.com/aspnet/EntityFramework.Docs/tree/master/samples/core/Querying/Querying

我写了一个解决方案,但我不知道这是否是解决此问题的好方法:

我创建了StudentCourse类并按如下所示对其进行了定义:

public class StudentCourse
{
    public int StudentCourseID { get; set; }

    public int StudentID { get; set; }
    public Student Student{ get; set; }

    public int CourseID { get; set; }
    public Course Course { get; set; }
}

然后我修改了Course类,如下所示:

public class Course
{
    public int CourseID { get; set; }

    public string Name { get; set; }

    public virtual ICollection<StudentCourse> Students { get; set; }
}
相关问题