0

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
renakre
  • 8,001
  • 5
  • 46
  • 99

1 Answers1

1

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?

Community
  • 1
  • 1
Paul Griffin
  • 2,416
  • 15
  • 19
  • thanks for the answer! I wonder if I would need to do this only for List type of properties of my classes. Let's say each discussion wall has only one member, and I have this property `public Person theMember`. Then, would I need to do the same not to get into trouble later? Is it recommended to define such properties this way when we create our class at first hand? – renakre Mar 07 '15 at 01:36
  • No, properties should be converted into columns by EF when it generates the database from your code. If you are trying to set up Members as a navigation property, there needs to be a reciprocal property in the class that it links to. Here's an example for a many-to-many relationship: http://www.codeproject.com/Articles/234606/Creating-a-Many-To-Many-Mapping-Using-Code-First – Paul Griffin Mar 07 '15 at 02:03
  • Sorry, just realizing now that was probably what you were trying to do in the first place... – Paul Griffin Mar 07 '15 at 02:04