问题描述
我试图从数据库中获取学生,并包括与他们相对应的课程实体,但是看来我做错了.
I am trying to get the students from the database and also include the course entities corresponding to them, but it seems that I'm doing something wrong.
这是学生班:
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; }
}
我检索了学生实体的集合,如下所示:
and I retrive the collection of student entities as shown below:
context.Students.Include(i => i.Course).ToList();
如果删除include方法,则会获取数据,但学生对象的课程属性为空.
If I remove the include method, then I get data, but course property of student object is null.
P.S我正在用Postman进行测试,而在包含"下我什么也收不到.
P.S I am testing it with Postman and with "Include" I am not able to get anything.
如果我对此发表评论
public virtual ICollection<Student> Students { get; set; }
一切正常.
我将完整的代码放在github上:
I put the full code on github:
https://github.com/AlexDev5/Problem
推荐答案
您必须配置序列化程序以忽略项目中的循环引用.
You have to configure the serializer to ignore circular references in your project.
为此,您必须在 Startup.cs
喜欢
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddJsonOptions(options => {
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
}
这篇关于无法包含导航属性(该属性为null)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!