Search code examples
c#linqentity-frameworkmany-to-many

"Object reference not set to an instance of an object error" when adding an item with Entity Framework Many-To-Many relationship


I am having an error about which I have no idea since it does not provide any details other than saying Object reference not set to an instance of an object error. I have a many-to-many relationship between Person and Course class, as defined below. When I attempt to add a new Person to a Course (i.e., enroll a student to a course), I get error in the line where Linq statement is executed. I provided the related sections of the code as follows:

Here is the code that throws an error:

Person userToRegister = _db.People.Single(p => p.Id == i.Value);//not null when debugging

int courseId = Convert.ToInt32(drp_Courses.SelectedValue);
Course myCourse = _db.Courses.Single(c => c.CourseId == courseId);//not null when debugging

myCourse.Members.Add(userToRegister);//This line throws the error
_db.SaveChanges();

Here is the Person class:

public class Person : IdentityUser
{
    [Required]
    [StringLength(50, ErrorMessage = "First name cannot be longer than 50 characters.")]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }

    public List<Course> RegisteredCourses { get; set; }
}

Here is the Course class:

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

    public string CourseTitle { get; set; }

    public List<Person> Members { get; set; }
}

Here is the definition of the relationship in DbContext class:

 modelBuilder.Entity<Course>()
                    .HasMany(c => c.Members)
                    .WithMany(p => p.RegisteredCourses)
                    .Map(m => m.MapLeftKey("CourseId").MapRightKey("Id")
                                                      .ToTable("EnrollmentsToCourse"));

Everything looks perfect to me. Can anyone tell me what I am missing here?


Solution

  • Change that line to

    Course myCourse = _db.Courses.Include(e => e.Members).Single(c => c.CourseId == courseId);
    

    And check

    if (myCourse.Members == null)
    {
        myCourse.Members = new List<Member>();
    }