Can't Include navigation property (it is null)

asp.net-web-api entity-framework-core

Question

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

1
1
7/22/2018 4:03:08 PM

Accepted Answer

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;
    });
}
0
7/23/2018 5:36:03 AM

Popular Answer

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow