1

I am trying to add a new student and after that, insert data into a junction table called 'AdditionalCourse' with the help of EF Core 3.1.

Whenever I add the junction rows (additional courses) by only using the foreign keys, it doesn't fill in the course property as expected after saving. It does fill in the Student property however.

Can someone figure out what I'm doing wrong?

I can solve this by just adding a 'get' call in between to just receive the freshly updated object, but I believe this is not necessary.

A minimal working prototype below:

Program.cs

static void Main(string[] args)
    {
        using (var context = new SchoolContext())
        {
            Course course = new Course("Spanish");
            context.Add(course);
            context.SaveChanges();
            Course course2 = new Course("French");
            context.Add(course2);
            context.SaveChanges();

            Student student = new Student("Bill");
            context.Add(student);
            context.SaveChanges();

            AdditionalCourse addCourse1 = new AdditionalCourse() { CourseId = course.Id, StudentId = student.Id };
            AdditionalCourse addCourse2 = new AdditionalCourse() { CourseId = course2.Id, StudentId = student.Id };
            student.AdditionalCourses.Add(addCourse1);
            student.AdditionalCourses.Add(addCourse2);

            context.SaveChanges();

            // Debug at this line
            var x = 0;
        }
    }

AdditionalCourse junction table

public class AdditionalCourse
{
    public int CourseId { get; set; }
    public Course Course { get; set; }

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

Student.cs

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<AdditionalCourse> AdditionalCourses { get; set; }

    public Student()
    {
    }

    public Student(string name)
    {
        Name = name;
        AdditionalCourses = new List<AdditionalCourse>();
    }
}

Course.cs

public class Course
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Course()
    {
    }

    public Course(string name)
    {
        Name = name;
    }
}

SchoolContext.cs

public class SchoolContext : DbContext
{
    public SchoolContext()
    { }

    public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
    { }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Data Source=SERVER_NAME;Initial Catalog=DATABASE_NAME;Integrated Security=True;");
    }

    public DbSet<Student> Students { get; set; }
    public DbSet<Course> Courses { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Student>().ToTable("student");
        modelBuilder.Entity<Course>().ToTable("course");
        modelBuilder.Entity<AdditionalCourse>().ToTable("additional_course");

        modelBuilder.Entity<AdditionalCourse>()
           .HasKey(x => new { x.CourseId, x.StudentId });
        modelBuilder.Entity<AdditionalCourse>()
           .HasOne(x => x.Student)
           .WithMany(x => x.AdditionalCourses)
           .HasForeignKey(x => x.StudentId);
        modelBuilder.Entity<AdditionalCourse>()
            .HasOne(x => x.Course)
            .WithMany()
            .HasForeignKey(x => x.CourseId);
    }
}
6
  • Are you adding a new student, that is not already stored (and got an id from your db)? How did you setup your entities references?
    – nilsK
    Dec 16, 2020 at 14:57
  • Updated the question, I forgot something. I am indeed adding a new student.
    – Faegav
    Dec 16, 2020 at 15:13
  • @Faegav Please edit your question to include a more detailed description of "receive an unexpected object". It is not clear what you mean by that. Also, is the Course object you expect already in the context you are using? Please provide a minimal reproducible example, which can be compiled and tested by others which shows that the navigation properties are not filled as expected.
    – Progman
    Dec 16, 2020 at 15:31
  • Done that now, I hope it's clear now.
    – Faegav
    Dec 16, 2020 at 16:31
  • @Faegav The issue is not reproducible with that code (assuming you replace SaveChangesAsync() with SaveChanges()).
    – Progman
    Dec 16, 2020 at 16:44

1 Answer 1

2

Whenever I add the junction rows (additional courses) by only using the foreign keys, it doesn't fill in the course property as expected after saving. It does fill in the Student property however.

By design, EF Core does not automatically load navigation properties. The only exceptions are when lazy loading is enabled and the navigation property getter is called, navigations to owned entities (or in EF Core 5.0+, navigations configured as AutoInclude) only when querying, or (which is the case with your Student property) the referenced object is already loaded (tracked) in the context. The later is called navigation property fixup, and can happen both during the query materialization or later.

Since you are not using lazy loading, the only guaranteed way to get navigation properties populated is to eager/explicit load them after.

For more info, see Loading Related Data section of the EF Core documentation.

1
  • That is a perfect answer to my question. I'm also gonna look into the latest EF Core 5.0+. At least I know how to solve it now. Thanks a lot!
    – Faegav
    Dec 17, 2020 at 8:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.