Search code examples
c#entity-frameworkmany-to-manyef-fluent-api

System.NullReferenceException when Inserting a new item for many-to-many relationship in entity framework


When adding an item for many-to-many relationship, I receive this error

An exception of type 'System.NullReferenceException' occurred in gEchoLu.dll but was not handled in user code

with no further details.

Here is the code that throws the exception:

protected void btn_AddMembers_Click(object sender, EventArgs e)
{
        gEchoLuDBContext _db = new gEchoLuDBContext();
        int wallId = Convert.ToInt32(grd_Walls.SelectedDataKey.Value);

        DiscussionWall selectedWall = _db.DiscussionWalls.Single(dw => dw.WallId == wallId);

        foreach (ListItem item in cbList_AllMembers.Items)
        {
            if (item.Selected)//if the checkbox item (i.e., user) is selected
            {
                Person selectedPerson = _db.People.Single(p => p.Id == item.Value.ToString());
//then retrieve the user from db

                selectedWall.Members.Add(selectedPerson);//**this line throws the error**
//add user to the selected wall
            }
        }

        _db.SaveChanges();

        BindWallMembers();
}

In the code above, when I debug it, I see that none of the instances (selectedWall and selectedPerson) are null. Here are the related sections of the related classes and the relationship among them:

public class DiscussionWall
{
    [Key]
    public int WallId { get; set; }

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

[Table("AspNetUsers")]
public class Person : IdentityUser
{
    public List<Course> RegisteredCourses { get; set; }
    public List<DiscussionWall> AttendedDiscussionWalls { get; set; }
}

Fluent api code:

modelBuilder.Entity<DiscussionWall>()
            .HasMany(dw => dw.Members)
            .WithMany(p => p.AttendedDiscussionWalls)
            .Map(m => m.MapLeftKey("WallId").MapRightKey("Id")
            .ToTable("EnrollmentsToDiscussionWalls"));

Does anyone have any idea what is wrong with my logic and code?


Solution

  • Looks like DiscussionWall.Members is null. It is not initialized to anything by your code. Try:

    private List<Person> _members;
    public List<Person> Members
    {
      get { return _members ?? (_members = new List<Person>()); }
      set { _members = value; }
    }
    

    See also: Why is my Entity Framework Code First proxy collection null and why can't I set it?