Can't Include navigation property (it is null)

2019-07-30 15:45发布

This question already has an answer here:

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.

this is student class:

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

    public string Name { get; set; }

    public int CourseID { get; set; }  

    public virtual Course Course { get; set; }
}

this is course class:

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();

If I remove the include method, then I get data, but course property of student object is null.

P.S I am testing it with Postman and with "Include" I am not able to get anything.

If I comment this

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

everything works fine.

I put the full code on github:

https://github.com/AlexDev5/Problem

2条回答
再贱就再见
2楼-- · 2019-07-30 16:49

You have to configure the serializer to ignore circular references in your project.

So for this you have to add following line of code inside ConfigureServices method in Startup.cs

Like

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
    .AddJsonOptions(options => {
        options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    });
}
查看更多
劫难
3楼-- · 2019-07-30 16:50

Depending on the sample found here https://github.com/aspnet/EntityFramework.Docs/tree/master/samples/core/Querying/Querying

I wrote one solution, but I don't know if it is good approach for this problem:

I created StudentCourse class and defined it as shown below:

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

And I modified the Course class as shown below:

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

    public string Name { get; set; }

    public virtual ICollection<StudentCourse> Students { get; set; }
}
查看更多
登录 后发表回答